Monday, December 26, 2011

Learning Scala : Reading the exotic and essential List API scaladoc 5

Authored by Win Myo Htet

``````def reduceLeft [B >: A] (f: (B, A) ⇒ B): B
def reduceLeftOption [B >: A] (op: (B, A) ⇒ B): Option[B]
def reduceRight [B >: A] (op: (A, B) ⇒ B): B
def reduceRightOption [B >: A] (op: (A, B) ⇒ B): Option[B]
``````
The different between reduceLeft and foldLeft is that reduceLeft does not have seed value to start with. Because of that reduceLeft will not yield a different collection, it just reduces the List collection to a single element. We also have self documenting function reduceLeftOption, which will return the nicely wrapped result in Option.
``````scala> val intlist=List(1,2,3,4,5)
intlist: List[Int] = List(1, 2, 3, 4, 5)

scala> intlist.reduceLeft{(sum,a)=>sum+a}
res0: Int = 15

scala> intlist.reduceLeft{(product,a)=>product*a}
res1: Int = 120

scala> val strlist=List("a","b","c","d","e")
strlist: List[java.lang.String] = List(a, b, c, d, e)

scala> strlist.reduceLeftOption{(res,str)=>res+str}
res2: Option[java.lang.String] = Some(abcde)

``````

We also have scanLeft which has different structure to reduceLeft. scanLeft takes an element as a seed value and return a collection of the result along with the seed value.
``````def scanLeft [B, That] (z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
def scanRight [B, That] (z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That
``````

``````scala> intlist
res3: List[Int] = List(1, 2, 3, 4, 5)

scala> intlist.scanLeft(0){(sum,a)=>sum+a}
res4: List[Int] = List(0, 1, 3, 6, 10, 15)

scala> intlist.scanLeft(1){(product,a)=>product*a}
res5: List[Int] = List(1, 1, 2, 6, 24, 120)

scala> strlist
res6: List[java.lang.String] = List(a, b, c, d, e)

scala> strlist.scanLeft(""){(sum,a)=>sum+a}
res7: List[java.lang.String] = List("", a, ab, abc, abcd, abcde)

``````
You might notice that the resulting List has one extra element from seed value and you will also notice that the function signature has an extra implicit argument for CanBuildFrom, which is beyond the scope of this series.  You can safely ignore it since it is implicit argument, compiler will look for the appropriate object for you.

Since I am very fond of foldLeft, I am confused with these extra functions : reduceLeft and scanLeft, then I remember about "do while", while, for and "for each". Talking about foreach, List also have foreach and forall as collection-traversing mechanism. ... Yeh, yeh, I have been outright ignoring some very relevant functions all these times. Let's talk about fold, reduce and scan first before we get to foreach and forall.

Authored by Win Myo Htet