logo

Scala - Functional Programming

Last Updated: 2021-11-19

map

scala> (1 to 5).map(_*2)
res6: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

reduce

scala> (1 to 5).reduce(_ + _)
res16: Int = 15

scala> (1 to 5).reduce((a, b) => a + b)
res17: Int = 15

scala> (1 to 5).reduceLeft(_ + _)
res9: Int = 15

foldLeft

scala> (1 to 5).foldLeft(0)(_ + _)
res13: Int = 15

scala> (1 to 5).foldLeft(0)((a, b) => a + b)
res15: Int = 15

scala> (1 to 5).foldLeft(1)((a, b) => a * b)
res18: Int = 120

foldLeft is a curried function

scala> var f = (1 to 5).foldLeft(0)(_)
f: ((Int, Int) => Int) => Int = <function1>

scala> f(_ + _)
res14: Int = 15

Cumulative Sum

scala> val a = Seq(1.0, 2.0, 3.0, 4.0)
a: Seq[Double] = List(1.0, 2.0, 3.0, 4.0)

scala> a.scanLeft(0.0)(_ + _)
res1: Seq[Double] = List(0.0, 1.0, 3.0, 6.0, 10.0)

scala> a.scanLeft(0.0)(_ + _).tail
res5: Seq[Double] = List(1.0, 3.0, 6.0, 10.0)