Spasski
Spasski

Reputation: 139

OCaml empty global variable

I'd like to know how do I define an empty! global variable of type Hashtbl in OCaml? I don't want to use Hashtbl.create because I don't know its initial size and I don't want to guess the initial size for performance reasons.

Basically this Hashtbl variable will be assigned a real Hashtbl in a function and then this variable will be shared among other functions so I don't want to pass it around as an argument all the time hence I'd like it to be global.

Upvotes: 5

Views: 2815

Answers (2)

0xFF
0xFF

Reputation: 4178

Hashtables in OCaml grow as needed, so you can just give a g best guess at first, for example :

module A

let hash = Hashtbl.create 123;;

...

let exceed_hash () = 
  for i = 1 to 555 do 
    Hashtbl.add hash i (string_of_int i) 
  done;;

Although you exceed the initial number but it will work smoothly too, check this tutorial for more info http://www.ocaml-tutorial.org/hashtbl

Upvotes: 7

Victor Nicollet
Victor Nicollet

Reputation: 24577

What you ask for is possible. You can define a global reference (this lets you assign it later on) to a hash table option (this lets you leave it uninitialized at first). The definition will look like this:

let hashtable = ref None

The initialization will be:

hashtable := Some (Hashtbl.create n)

To use it, you will also have to explain what should happen if you haven't initialized it yet:

match !hashtable with 
  | None -> assert false
  | Some h -> frobnicate h

In practice, uninitialized variables are against the OCaml philosophy and will only make your life harder. I strongly advise you not to use this approach. My two suggestions would be:

  • Determine the performance loss caused by creating a hash table with a guessed size. The overhead might be much smaller than you think.

  • Just pass the hash table everywhere. It's a single argument, which is shorter than an option reference...

  • Put your hash table and the functions using it in a class.

Upvotes: 5

Related Questions