Scala turn right and turn left

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.

+4
source share
2

, - , :

List(1, 3, 8).foldLeft(100)(_ - _) == ((100 - 1) - 3) - 8 == 88
List(1, 3, 8).foldRight(100)(_ - _) == 1 - (3 - (8 - 100)) == -94

, foldLeft/Right . , , , .

+7

, , . ? , , , , .. ..

.

List(1,2,3,4,5).foldLeft(0)(_ + _)

"+" - , , , - . " " , - 0, .

, fold,

List(1,2,3,4,5).foldLeft(1)(_ * _)

Fold , .

, ScalaDoc foldLeft foldRight.

+1

Source: https://habr.com/ru/post/1662059/


All Articles