OCaml By Examples

hash tables


Hashtbl are OCaml's hashmaps (also called associative arrays or dictionaries). To create a hashtbl you need to specify an initial size (here 10). Don't worry too much about this as it'll expand by itself if you try to store more than 10 elements. Also note that you always need to pass `~random:true`, as unfortunately the default usage of this function is not secure.
utop # let balances = Hashtbl.create ~random:true 10;;
val balances : ('_weak1, '_weak2) Hashtbl.t = <abstr>
You can add values to your hashtable
utop # Hashtbl.add balances "david" 2;;
- : unit = ()
`add` updates the value if it already exists
utop # Hashtbl.add balances "david" 3;;
- : unit = ()
You can retrieve value with `find_opt`.
utop # Hashtbl.find_opt balances "alice";;
- : int option = None

utop # Hashtbl.find_opt balances "david";;
- : int option = Some 3
next: modules