Ocaml and Hashtables
Coming from a Perl background and seeing the Ocaml Hashtbl documentation for the first time, it can be really confusing. Especially since there is no keys, values, and each functions in the documentation. So, first of all while Ocaml doesn’t give you these functions out of the box and I would argue that it should, you can write them fairly easily yourself using the fold function.
let keys htbl =
Hashtbl.fold (fun k _ accum -> k::accum) htbl []
As you can see above the fold function gets three params, the first two are the key and value. The third is the “accumulator” or in this case just a list where you will append the k variable. The underscore means “anything” and tells the compiler that you don’t really care about the binding and it is not then necessary.
The values function works similarly.
let values htbl =
Hashtbl.fold (fun _ v accum -> v::accum) htbl []
The each function will be slightly different in that we need both k and v and the accum parameters.
let each htbl =
Hashtbl.fold (fun k v accum -> (k, v)::accum) []
This creates a list of tuples of the key and value. You can then match against it and get the key and value out.
Leave a comment