map, flatMap, filter and fold

Four methods cover most of what a program does with a collection. map changes every element, filter keeps some of them, flatMap changes every element into a collection and joins the results, and foldLeft walks the collection with a value that carries the answer so far. collect is the pair of filter and map written as one pattern match.

map, filter, flatMap and collect

Order holds a quantity and a price, and its total is a method on the case class. The four transformations read as one line each, and none of them changes the list it starts from:

transforms.scala

case class Order(item: String, quantity: Int, price: Int): def total: Int = quantity * price @main def transforms(): Unit = val orders = List( Order("keyboard", 2, 49), Order("mouse", 1, 19), Order("monitor", 3, 129) ) println(orders.map(_.total)) println(orders.filter(_.quantity > 1).map(_.item)) println(orders.flatMap(order => List.fill(order.quantity)(order.item))) println(orders.collect { case Order(name, quantity, _) if quantity > 1 => name }) println(orders.map(_.item).mkString(" | "))

scala-cli run --server=false transforms.scala

List(98, 19, 387)
List(keyboard, monitor)
List(keyboard, keyboard, mouse, monitor, monitor, monitor)
List(keyboard, monitor)
keyboard | mouse | monitor

flatMap is the one that needs a moment: List.fill(order.quantity)(order.item) makes a list of repeated names per order, and flatMap joins the lists into one, so a keyboard ordered twice appears twice. collect takes a partial function: a pattern that fits only some elements, with the guard inside it. Its result is the same as a filter followed by a map, written once.

Folding a collection to one value

A fold carries an accumulator through the collection. foldLeft goes from the first element to the last and foldRight from the last to the first, which matters as soon as the operation is not commutative. The accumulator may be another collection, and then a fold is a grouping:

folds.scala

@main def folds(): Unit = val numbers = List(1, 2, 3, 4, 5) println(numbers.foldLeft(0)(_ + _)) println(numbers.foldRight(0)(_ + _)) println(numbers.fold(0)(_ + _)) println(numbers.reduce(_ + _)) println(numbers.sum) println(numbers.product) println(numbers.foldLeft(List.empty[Int])((acc, n) => n :: acc)) val words = List("the", "quick", "brown", "fox") val byLength = words.foldLeft(Map.empty[Int, List[String]]) { (acc, word) => acc.updated(word.length, word :: acc.getOrElse(word.length, Nil)) } println(byLength.toList.sortBy(_._1)) println(words.foldLeft("")((acc, word) => if acc.isEmpty then word else s"$acc $word"))

scala-cli run --server=false folds.scala

15
15
15
15
15
120
List(5, 4, 3, 2, 1)
List((3,List(fox, the)), (5,List(brown, quick)))
the quick brown fox

foldLeft(List.empty[Int])((acc, n) => n :: acc) reverses the list in one pass, because each element goes in front of the accumulator. reduce is a fold whose accumulator is the first element, so it throws on an empty collection where fold has a starting value to return. sum and product are folds with a name, and the grouping by word length is the same fold with a map as the accumulator — the next lesson does it with groupBy.

Related

Article author: Arthur Isaev