Produce a new value from an array.
fold
takes two arguments, an initial
'accumulator' value and a function f
.
For each element of the array f
will be called with two arguments: the current accumulator and an element.
f
returns the value that the accumulator should have for the next iteration.
The initial
value is the value the accumulator will have on the first call to f
.
After applying f
to every element of the array, fold
returns the accumulator.
fold
iterates over the elements of the array from first to last.
Folding is useful whenever you have a collection of something, and want to produce a single value from it.
For example, if we have:
let numbers = [|1, 2, 3|] in
let sum =
Array.fold numbers ~initial:0 ~f:(fun accumulator element -> accumulator +element)
in
sum = 6
Walking though each iteration step by step:
accumulator: 0, element: 1, result: 1
accumulator: 1, element: 2, result: 3
accumulator: 3, element: 3, result: 6
And so the final result is 6
. (Note that in reality you probably want to use Array.sum
)
Examples
Array.fold [|3;4;5|] ~f:Int.multiply ~initial:2 = 120
Array.fold [|1; 1; 2; 2; 3|] ~initial:Set.Int.empty ~f:Set.add |> Set.to_array = [|1; 2; 3|]
let last_even integers =
Array.fold integers ~initial:None ~f:(fun last int ->
if Int.is_even then
Some int
else
last
)
in
last_even [|1;2;3;4;5|] = Some 4