typestar

Plegar en Scala

Los pesos de unas cajas plegados a un total, luego a una cadena y a un Map.

// foldLeft takes a starting value and walks left to right, passing
// the accumulator and the next element to the function each step
val crateWeights: List[Int] = List(120, 340, 75, 210)
val totalKg: Int = crateWeights.foldLeft(0)((acc, kg) => acc + kg)

// sum and max are that same fold under shorter names
val alsoTotal: Int = crateWeights.sum
val heaviest: Int = crateWeights.max

// reduce needs no start value, so it fails on an empty list
val byReduce: Int = crateWeights.reduce((a, b) => a + b)

// the accumulator can have a type of its own, unlike the elements
val manifest: String =
  crateWeights.foldLeft("crates:")((acc, kg) => s"$acc $kg kg")

// folding into a Map builds up an index one element at a time
val tonnage: Map[Int, Double] =
  crateWeights.foldLeft(Map.empty[Int, Double]): (acc, kg) =>
    acc.updated(kg, kg / 1000.0)

Cómo funciona

  1. crateWeights.foldLeft(0) hila un acumulador de izquierda a derecha desde un inicio; sum es ese fold abreviado.
  2. crateWeights.reduce((a, b) => a + b) no recibe valor inicial, y por eso no tiene qué devolver con una lista vacía.
  3. foldLeft("crates:") acumula un String y el último fold en Map.empty[Int, Double], ninguno del tipo Int.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
20
Caracteres a escribir
841
Tokens
147
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 126 segundos.

Escribe este fragmento

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

← Anterior Siguiente →