FoldLeft using FoldRight in scala

后端 未结 4 1569
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 13:46

While going through Functional Programming in Scala, I came across this question:

Can you right foldLeft in terms of foldRight? How about the other way

4条回答
  •  攒了一身酷
    2021-01-30 14:04

    That code is chaining several function objects together, one function for each element in the list. Here is an example that shows that more clearly.

    val f = (a: Int, b: Int) => a+b
    val list = List(2,3,4)
    println(list.foldLeft(1)(f))
    
    val f1 = (b: Int) => f(b, 2)
    val f2 = (b: Int) => f(b, 3)
    val f3 = (b: Int) => f(b, 4)
    val f4 = (b: Int) => b
    
    val ftotal = f1 andThen f2 andThen f3 andThen f4
    println(ftotal(1))
    

    You can imagine that as a linked list of function objects. When you pass in a value it "flows" through all the functions. It's a little like dataflow programming.

提交回复
热议问题