Let’s say we have two types: , .
Also, let’s say we have operator +, for which += and +=. Then, speaking in types:
val a = List(, , , )
a.reduceLeft( (, ) => + ) : ==
((+)+)+
a.foldLeft()( (,) => + ) : ==
(((+)+)+)+
Edge cases:
val b = List[]() //empty list of
b.reduceLeft(_+_) //throw exception
b.foldLeft()(_+_) //returns
val c = List[]() //list of single
c.reduceLeft(_+_) // returns , the single element in the list
c.foldLeft()(_+_) //returns , result of operation +
Notice the difference: when list is empty, reduceLeft throws an exception, while foldLeft returns starting value. This can often help to decide which one to use.
Examples:
val a = List(1, 2, 3, 4)//sum of integers in the listval sum = a.reduceLeft( (u, v) => u+v )//integers in the list separated by comma, using reduceval strRepr1 = a.map( u => u.toString() ).reduceLeft( (u, v) => u+","+v )
//sum of squares, we use Long to support larger valuesval sqrSum = a.foldLeft(0L)( (u, v)=> u+v*v )//number if items in the listvar count = a.foldLeft(0) ( (u, v) => u+1 )//integers in the list separated by comma, using foldval strRepr2 = a.tail.foldLeft(a.head.toString())( (u, v) =>u+","+v )