对于下面的示例,有人可以解释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?
谢谢。
答案 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
)