I try to learn functional programming and Scala, so I read "Functional Programming in Scala" by Chiusano and Bjarnason. I am having trouble understanding what is folding left and dumping the correct methods in case of a list. I looked around here, but I did not find anything new. Thus, the code provided by this book:
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B = as match {
case Nil => z
case Cons(h, t) => f(h, foldRight(t, z)(f))
}
def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = l match {
case Nil => z
case Cons(h,t) => foldLeft(t, f(z,h))(f)
}
Where is minus and nil:
case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]
So what actually stacks left and right? Why are “useful” methods needed? There are many other methods that use them, and it is also difficult for me to understand them, since I do not get these two.
source
share