I was reading the documentation for Map.fold
from the following link:
val fold : (key -> 'a -> 'b -> 'b) -> 'a t -> 'b -> 'b
Is this function similar to List.fold_left
? I'm a neophyte to OCaml and find the description of arguments for functions difficult to parse. My understanding is that Map.fold
applies a function to entries in a map and then stores those entries in a new map, or some kind of accumulator. Is this a correct understanding? I know that 'a
signifies a value of any type - does 'b
signify a new value transformed by a function?
Map.fold
is very much like List.fold_left
. Note that List.fold_left
does not, in and of itself, produce a new list. It's more general than that--it maintains a value of any desired type as it processess the elements of a list.
Similarly, Map.fold
incrementally computes a value of any desired type (the type 'b
in the type signature you give) as it processes the elements of the map.
To make this work, you supply a function of three arguments that processes one element of the map. The first argument is the key for the map element. The second argument is the value of the map element. The third argument is the current value that is being incrementally computed. The return value of the function is the new incrementally computed value.
After all the map elements have been processed Map.fold
returns the final value of type 'b
.
Here is a function that adds up the elements of a list with List.fold_left
:
let list_sum l =
List.fold_left (+) 0 l
When building a map you need to specify the type of the keys. Here's a function that adds up the values of a map whose keys are strings:
module StringMap = Map.Make(String)
let map_sum m =
StringMap.fold (fun k v accum -> v + accum) m 0