Is it possible to store different types in the same hashtable (Hashtbl
) in Ocaml? Are hashtables really restricted to just one type?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With