El for con yield en Scala
Las hileras de un huerto convertidas en colecciones nuevas con for y yield.
// for-yield walks a collection and builds a new one from the results
val rows: List[Int] = List(1, 2, 3, 4)
val spaced: List[Int] = for row <- rows yield row * 3
// a guard sits after the generator and drops what it rejects
val evenRows: List[Int] = for row <- rows if row % 2 == 0 yield row
// two generators nest, the second running once per outer element,
// and the yield sees both bindings at once
val plots: List[(Int, String)] =
for
row <- rows
tree <- List("plum", "quince")
yield (row, tree)
// the result follows the first generator, so a Set yields a Set
val grafts: Set[Int] = for tag <- Set(3, 1, 3) yield tag + 100
Cómo funciona
for row <- rows yield row * 3recorre la lista y junta cada resultado en una lista nueva.for row <- rows if row % 2 == 0 yield rowpone una guarda tras el generador y descarta lo que rechaza antes del yield.row <- rowsytree <- Listanidan y dan pares(row, tree); conSet(3, 1, 3)el yield da unSet.
Palabras clave y builtins usados aquí
forifvalyield
El intento, en números
- Líneas
- 17
- Caracteres a escribir
- 632
- Tokens
- 112
- Ritmo de tres estrellas
- 75 tpm
Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 90 segundos.
Paso 3 de 3 en Transformaciones; paso 15 de 27 en Fundamentos del lenguaje.