Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying hashtable as a userdefined type in OCaml

Tags:

types

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?

like image 711
krandiash Avatar asked Mar 10 '13 12:03

krandiash


People also ask

Why can’t I use hashtable in OCaml?

That’s because the requirement for multiple objects to share a comparison function or a hash function mostly just doesn’t come up for hash tables. That makes building a module suitable for use with a hash table simpler. You can also create a hashtable based on OCaml’s polymorphic hash and comparison functions.

What is OCaml for the skeptical?

OCaml for the Skeptical: User-Defined Types OCaml for the Skeptical U of C Library DLDC Informal OCaml Class User-Defined Types We've seen OCaml's type syntaxbecause the interpreter uses it to tell you the type of every value, but due to type inference we typically don't have to write a type expression ourselves.

How do you name a type in OCaml?

Since types are also something you can manipulate in OCaml, there is a mechanism for naming them as well. This is done with the keyword type. The simplest kind of type definition is an alias for a type that already exists. Suppose that we like int list's so much that we want to give them a shorter name.

What is the initial size of the Hashtable?

The 123456 is the initial size of the hashtbl. This initial number is just your best guess as to the amount of data that you will be putting into the hash table. The hash table can grow if you under-estimate the size so don't worry about it too much.


1 Answers

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.

like image 74
gasche Avatar answered Nov 05 '22 15:11

gasche