Sunday, November 23, 2014

Scala Code Review: foldLeft and foldRight | Matt Malone's Old-Fashioned Software Development Blog


Scala Code Review: foldLeft and foldRight | Matt Malone's Old-Fashioned Software Development Blog
def foldLeft[B](z: B)(f: (B, A) => B): B
Firstly, foldLeft is a curried function (So is foldRight). If you don’t know about currying, that’s ok; this function just takes its two parameters (z and f) in two sets of parentheses instead of one. Currying isn’t the important part anyway.
The first parameter, z, is of type B, which is to say it can be different from the list contents type. The second parameter, f, is a function that takes a B and an A (a list item) as parameters, and it returns a value of type B. So the purpose of function f is to take a value of type B, use a list item to modify that value and return it.
The foldLeft function goes through the whole List, from head to tail, and passes each value to f. For the first list item, that first parameter, z, is used as the first parameter to f. For the second list item, the result of the first call to f is used as the B type parameter.
list.foldLeft(List[Int]())((b,a) => a :: b)

Read full article from Scala Code Review: foldLeft and foldRight | Matt Malone's Old-Fashioned Software Development Blog

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.