I'm learning OCaml. Currently, I'm going through some of the default iterator implementations for Lists and I'm a little confused about one part of fold_left
.
let rec fold_left f accu l =
match l with
[] -> accu
| a::l -> fold_left f (f accu a) l
The part I'm confused about is (f accu a)
. I'll break it down to the extent of my understanding.
f
is the function passed to fold_left
that should be applied to each element in the list. accu
is the accumulator that keeps track of the folded sum. a
is the element at the head of l
, the list passed to fold_left
.Why is the accumulator being passed to f
? Shouldn't it be the sum of the accumulator and the return value of f a
?
And how does all of this return a single int
, which is what the accumulator should be (assumedly)?
A fold is completely general, it's not just for adding up numbers.
The function f
can be any function that takes an accumulated value (of any type) and a new value from the list, and returns a new accumulated value. That's the only requirement.
You can imagine fold_left f init [a; b; c; d]
as a short way to write this expression:
f (f (f (f init a) b) c) d
Again, f
can be any function whose type is correct for the accumulated value and the list elements.