Identifying hashtable as a userdefined type in OCaml

ocaml, types

Solution

It makes no sense to declare type synonyms and to expect the compiler to use either one expression or the other in precise situations: as they are equal types, the compiler will use either one and you have little control on that.

If you want to enforce type abstraction, so as to not mix a type `my_type` with any other `(string, int) Hashtbl.t`, you should define a new type with a constructor marking the difference:

type my_type = Tbl of (string, int) Hashtbl.t
let a = Tbl (Hashtbl.create 100)
let add (Tbl t) k v = Hashtbl.add t k v

You may want this (and pay the cost of having to transform all values of `my_type` into hashtables by explicit pattern-matching when you want to use one of the `Hashtbl` function), or you may want to manipulate only a type synonym, but in the latter case you should not expect the compiler output to report any particular type.

Problem

I want to be able to define a type (say my_type) which can identify hashtables with strings as keys and mapped to integer values. So, I tried ``` # type my_type = (string, int) Hashtbl.t;; ``` But, when I try ``` # let a = Hashtbl.create 100;; val a : ('_a, '_b) Hashtbl.t = <abstr> # Hashtbl.add a "A" 12;; - : unit = () # a;; - : (string, int) Hashtbl.t = <abstr> ``` The last line shows (string, int) Hashtbl.t = abstr instead of my_type. How can I make sure it gives me the type of the hashtable as my_type?

Original source