Folding in Scala
Crate weights collapsed to a total, then to a string and to a 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)
How it works
crateWeights.foldLeft(0)((acc, kg) => acc + kg)threads an accumulator left to right from a starting value, andcrateWeights.sumis that same fold under a shorter name.crateWeights.reduce((a, b) => a + b)takes no starting value, which is why it has nothing to return for an empty list.crateWeights.foldLeft("crates:")accumulates aStringand the last fold accumulates intoMap.empty[Int, Double], neither of them matching theIntelement type.
Keywords and builtins used here
DoubleIntListMapStringval
The run, in numbers
- Lines
- 20
- Characters to type
- 841
- Tokens
- 147
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 126 seconds.
Step 2 of 3 in Transformations, step 14 of 27 in Language basics.