scala-foldLeft-vs-foldRight.md
Definition of foldLeft
and foldRight
foldLeft
please notice the definition of op
: (op: (B, A) => B)
here, A
is the element of the caller, B
is the intermedia result of function op
foldRight
Example
foldLeft
1 | class Foo(val name: String, val age: Int, val sex: Symbol) |
the result is :
1 | stringList: List[String] = List(Mr. Hugh Jass, 25, Mr. Biggus Dickus, 43, Ms. Incontinentia Buttocks, 37) |
foldRight
1 | val stringList2 = fooList.foldRight[List[String]](List[String]()) { (z, f) => |
you would get error:
1 | Error:(34, 23) value sex is not a member of List[String] |
why ?
notice this code snippet : { (z, f) => }
for foldRight
, f
is the intermedia result of the function, of course he would have the sex
symbol.
so we need to switch them like this:
1 | val stringList2 = fooList.foldRight[List[String]](List[String]()) { (f, z) => |
result:
1 | stringList2: List[String] = List(Ms. Incontinentia Buttocks, 37, Mr. Biggus Dickus, 43, Mr. Hugh Jass, 25) |