typestar

Map and filter in Scala

Bakery order counts run through map and filter, alone and chained.

// map applies a function to every element and returns a new List
val loaves: List[Int] = List(2, 5, 1, 8, 3)
val doubled: List[Int] = loaves.map(order => order * 2)

// _ stands in for the parameter when it appears exactly once
val plusOne: List[Int] = loaves.map(_ + 1)

// filter keeps the elements whose predicate answers true
val bigOrders: List[Int] = loaves.filter(_ >= 3)

// the two chain, each stage handing a fresh List to the next
val boxedBig: List[Int] = loaves.filter(_ > 2).map(_ * 12)

// map may return a different element type, here Int to String
val labels: List[String] = loaves.map(order => s"$order loaves")

// filtering first leaves the map less work to do
val shortLabels: List[String] =
  loaves.filter(_ < 4).map(order => order.toString)

How it works

  1. loaves.map(order => order * 2) names its lambda parameter, while loaves.map(_ + 1) writes _ for a parameter used exactly once.
  2. loaves.filter(_ >= 3) keeps the orders whose predicate answers true, and loaves.filter(_ > 2).map(_ * 12) chains the two so each stage hands a fresh list to the next.
  3. loaves.map(order => s"$order loaves") produces a List[String], so the element type of the result need not match the input.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
763
Tokens
144
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 123 seconds.

Type this snippet

Step 1 of 3 in Transformations, step 13 of 27 in Language basics.

← Previous Next →