All Articles

Reduce

Intro

I briefly discussed fold in my post on tail-recursion. I introduced foldLeft as a blackbox for tail-recursion.

Ex

  val x: List[Int] = List(1, 2, 3)
  val y: Int = x.foldLeft(0)((sum, x) => sum + x)
  println(y)  // 6

reduce

In my post on the flatten method I showed how foldLeft can be used for more general purposes such as flattening a list of lists.

In fact, many use-cases of foldLeft simply involve basic arithmetic computations where the seed parameter is initialized to 0. Some syntactic sugar exists for this. Namely, reduceLeft.

Ex 1

  val x: List[Int] = List(1, 2, 3)
  val y: Int = x.reduceLeft(_+_)
  println(y)  // 6

Ex 2

  val x: List[Int] = List(1, 2, 3)
  val y: Int = x.reduceLeft(_*_)
  println(y)  // 6
Published 9 Jul 2018