Could someone explain how currying happens in foldLeft for the below example:
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]
My Understanding is:
(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?
Thanks.
Step by step:
foldLeft
on a List[A]
has a signature foldLeft[B](b: B)(f: (B, A) => B): B
list: List[A]
and b: B
, the curried expression list.foldLeft(b) _
would have type ((B, A) => B) => B
numbers
has type List[Int]
, thus A
is inferred to be Int
List[Int]()
has type List[Int]
, thus B
is inferred to be List[Int]
Int
for A
and List[Int]
for B
in ((B, A) => B) => B
, you obtain (List[Int], Int) => List[Int]) => List[Int]
. That's exactly what the compiler gives you. In words:
(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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.