Is it possible to store different types in the same hashtable (Hashtbl) in Ocaml? Are hashtables really restricted to just one type?
Is it possible to store different types in the same hashtable ( Hashtbl )
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
A value of type (string, alg) Hashtbl.t would store ints and floats, using a string as the lookup key.
After you get used to the flexible and strong typing of OCaml, it’s hard to go back to systems without it.