typestar

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

  1. for row <- rows yield row * 3 recorre la lista y junta cada resultado en una lista nueva.
  2. for row <- rows if row % 2 == 0 yield row pone una guarda tras el generador y descarta lo que rechaza antes del yield.
  3. row <- rows y tree <- List anidan y dan pares (row, tree); con Set(3, 1, 3) el yield da un Set.

Palabras clave y builtins usados aquí

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.

Escribe este fragmento

Paso 3 de 3 en Transformaciones; paso 15 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →