fold
and reduce
Some common iterative program patterns:
Move through a list left-to-right, computing a new store:
fold
fold
“folds” the members of a list left-to-right using its first argument, given an initial value, so
and
what about fold (fun t h -> h::t) [] [1; 2; 3]
?
In Ocaml this is also called “fold left”, or List.fold_left
What is the type of fold(_left)
?
How is it implemented in Ocaml?
Example: implement length
via fold
:
reduce
reduce
processes the members of a list by reducing the tail, combining with its first argument so:
and
What about reduce (fun h t -> h::t) [1; 2; 3] []
?
In Ocaml this is also called “fold right”, or List.fold_right
What is the type of reduce
?
How is it implemented in Ocaml?
Example: implement flatten : 'a list list -> 'a list
via reduce:
More examples:
distinct: 'a list -> 'a list
listmax: 'a list -> 'a option
implode: char list -> string
(note: String.make 1 c turns c into a string)
Which are better with fold
? With reduce
?
cs2041.org