module Hashtbl: sig
.. end
For many students of ocaml, using hashtables is complicated by the
functors. Here are a few tips:
For a list of hashtable functions see Hashtbl_intf.S
.
To create a hashtable with string keys use String.Table.
let table = String.Table.create () ~size:4 in
List.iter ~f:(fun (key, data) -> Hashtbl.set table ~key ~data)
[ ("A", 1); ("B", 2); ("C", 3); ];
Hashtbl.find table "C"
Here 4 need only be a guess at the hashtable's future size.
There are other similar pre-made hashtables, eg
Int63.Table or Symbol.Reuters.Table.
To create a hashtable with a custom key type use Hashable.
module Key = struct
module T = struct
type t = String.t * Int63.t with sexp
let equal = (=)
let hash = Hashtbl.hash
end
include T
include Hashable.Make (T)
end
let table = Key.Table.create () ~size:4 in
List.iter ~f:(fun (key, data) -> Hashtbl.set table ~key ~data)
[ (("pi", Int63.zero), 3.14159);
(("e", Int63.minus_one), 2.71828);
(("Euler", Int63.one), 0.577215);
];
Hashtbl.find table ("pi", Int63.zero)
Performance may improve if you define equal
and hash
explicitly, eg:
let equal (x, y) (x', y') = String.(=) x x' && Int63.(=) y y'
let hash (x, y) = String.hash x + Int63.hash y * 65599
module Hashable: Core_hashtbl_intf.Hashable
val hash : 'a -> int
val hash_param : int -> int -> 'a -> int
type ('a, 'b)
t
val sexp_of_t : ('a -> Sexplib.Sexp.t) ->
('b -> Sexplib.Sexp.t) -> ('a, 'b) t -> Sexplib.Sexp.t
include Creators
include Accessors
module Poly: sig
.. end
with type ('a, 'b) t = ('a, 'b) t
module type Key = Core_hashtbl_intf.Key
module type S = S
with type ('a, 'b) hashtbl = ('a, 'b) t
module type S_binable = S_binable
with type ('a, 'b) hashtbl = ('a, 'b) t
module Make (
Key
:
Key
)
: S
with type key = Key.t
module Make_binable (
Key
:
sig
include Hashtbl.Key
include Binable.S
end
)
: S_binable
with type key = Key.t