scala:scala如何将foldLeft转换为currying函数

时间:2018-07-15 21:03:36

标签: scala

对于下面的示例,有人可以解释foldLeft中的如何进行咖喱化。

val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val numberFunc = numbers.foldLeft(List[Int]())_
>numberFunc: ((List[Int], Int) => List[Int]) => List[Int] 

我的理解是:

(List[Int], Int) - (accumulator which in this case is empty List, each element of the numbers list)
=> List[Int]     - which is the output numberFunc list.
=> List[Int]     - what does this represent? 

谢谢。

1 个答案:

答案 0 :(得分:3)

逐步:

    foldLeft上的
  • List[A]具有签名foldLeft[B](b: B)(f: (B, A) => B): B
  • 因此,通常,对于list: List[A]b: B,咖喱表达式list.foldLeft(b) _的类型为((B, A) => B) => B
  • numbers的类型为List[Int],因此A被推断为Int
  • List[Int]()的类型为List[Int],因此B被推断为List[Int]
  • Int中用A替换List[Int],用B替换((B, A) => B) => B,得到(List[Int], Int) => List[Int]) => List[Int]。这正是编译器为您提供的。

换句话说:

  (numberFunc :                       // `numberFunc` is a function that
     (                                // given a function that
       (List[Int], Int)               //   takes an accumulator and an int
       =>                             //   and produces 
       List[Int]                      //   an updated list of ints
     )
     =>                               // produces
     List[Int]                        // a list of ints
  )