Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashtables in ocaml

Is it possible to store different types in the same hashtable (Hashtbl) in Ocaml? Are hashtables really restricted to just one type?

like image 666
pbp Avatar asked Jan 22 '12 17:01

pbp


1 Answers

Yes, hash tables entries are restricted to one type for each table. This is really a question about the OCaml type sytem and not about hash tables. If it seems odd to require things to be the same type in a hash table, how about in a list?

Without knowing the problem you're solving, it's hard to know what to suggest. However, a common thing to do is to create an algebraic type that has one variant for each of the types you're dealing with:

type alg = A of int | B of float

A value of type (string, alg) Hashtbl.t would store ints and floats, using a string as the lookup key.

# let ht = Hashtbl.create 44;;
val ht : ('_a, '_b) Hashtbl.t = <abstr>
# Hashtbl.add ht "yes" (A 3);;
- : unit = ()
# Hashtbl.add ht "no" (B 1.7);;
- : unit = ()
# ht;;
- : (string, alg) Hashtbl.t = <abstr>
# Hashtbl.find ht "yes";;
- : alg = A 3

After you get used to the flexible and strong typing of OCaml, it's hard to go back to systems without it.

like image 98
Jeffrey Scofield Avatar answered Oct 08 '22 23:10

Jeffrey Scofield