Scala Reactive Programming
上QQ阅读APP看书,第一时间看更新

FRP – the reduce() function Marble diagram

Now we will see another important and frequently used functional HOF, that is, reduce().

It takes each element from the data stream (or container) and applies the given function. Let's do it with List (almost all containers have this function):

scala> val numList = List(1,2,3,4,5,6) 
numList: List[Int] = List(1, 2, 3, 4, 5, 6) 
 
scala> numList.reduce((x,y) => x +y ) 
res22: Int = 21 
 
scala> numList.reduce(_ + _) 
res21: Int = 21 

The following diagram shows the Marble diagram for the reduce() function:

If you are new to HOF, refer to Chapter 2, Functional Scala, for more information.