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.
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:
The initialization will be:
To use it, you will also have to explain what should happen if you haven’t initialized it yet:
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.