Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hash table to list of pairs (key,value) in OCaml

Is there a way of converting a hash table into a list of (key,pair) values in OCaml?

I'm aware that, given a hash table ht we can do

BatList.of_enum (BatHashtbl.enum ht)

using the batteries library. This would convert the table to an enumeration and then convert the enum to a list. But I'm looking for a solution that doesn't use the Batteries Library. In the standard OCaml Hashtbl Module there doesn't seem to be a way of extracting the pairs as a list or a way of combining its functions to achieve this purpose. Any suggestions?

like image 877
Surikator Avatar asked Oct 30 '10 18:10

Surikator


1 Answers

In the standard OCaml Hashtbl Module there doesn't seem to be ...

Of couse there is!

val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c

So, use:

fun h -> Hashtbl.fold (fun k v acc -> (k, v) :: acc) h []
like image 193
Pascal Cuoq Avatar answered Nov 03 '22 16:11

Pascal Cuoq