typestar

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

  1. crateWeights.foldLeft(0)((acc, kg) => acc + kg) threads an accumulator left to right from a starting value, and crateWeights.sum is that same fold under a shorter name.
  2. crateWeights.reduce((a, b) => a + b) takes no starting value, which is why it has nothing to return for an empty list.
  3. crateWeights.foldLeft("crates:") accumulates a String and the last fold accumulates into Map.empty[Int, Double], neither of them matching the Int element type.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Transformations, step 14 of 27 in Language basics.

← Previous Next →