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.
In other words, the value of a variable cannot change in OCaml. Rather, all mutations must occur through data structures.
Well, val is a keyword in OCaml with several different uses. The cases you mention are both, in essence, that val is used in a module signature to specify values that appear in the module. Values are things like functions and expressions.
At its simplest, a variable is an identifier whose meaning is bound to a particular value. In OCaml these bindings are often introduced using the let keyword. We can type a so-called top-level let binding with the following syntax. Note that variable names must start with a lowercase letter or an underscore.
let x = 42. val x : int = 42. Similarly, OCaml functions do not have to have names; they may be anonymous. For example, here is an anonymous function that increments its input: fun x -> x + 1 . Here, fun is a keyword indicating an anonymous function, x is the argument, and -> separates the argument from the body.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With