krandiash
krandiash

Reputation: 165

Identifying hashtable as a userdefined type in OCaml

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?

Upvotes: 10

Views: 1571

Answers (3)

octref
octref

Reputation: 6801

Update: sorry, as gasche points out, you can use a simple type annotation to do that, forget about the type coercion

# type my_type = (string, int) Hashtbl.t;;
type my_type = (string, int) Hashtbl.t
# let (a : my_type) = Hashtbl.create 100;;
val a : my_type = <abstr>

Upvotes: 2

gasche
gasche

Reputation: 31459

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.

Upvotes: 9

jrouquie
jrouquie

Reputation: 4405

my_type is just a synonym for (string, int) Hashtbl.t, you can use both interchangeably.

You can tell the compiler that a is of type my_type, and get nicer output, this way:

# let (a:my_type) = Hashtbl.create 100;;
val a : my_type = <abstr>
# a;;
- : my_type = <abstr>

If you're wondering about <abstr>, it means that the toplevel doesn't know how to print a (its content, not its type).

Upvotes: 1

Related Questions