OCaml Search Tables

I would like to create a lookup table in OCaml. The table will contain 7000+ records, which after searching (by int) will return a string. What suitable data structure is used for this task? If the table should be inferred from the base code, and if so, how to make a “including” lookup table accessible from his / her program?

Thanks.

+5
source share
3 answers

If strings are addressed using consecutive integers, you can use an array.

Otherwise, you can use a hash table (non-functional) or a map (functional). To get started with the map, try:

module Int =
struct
  type t = int
  let compare = compare
end ;;

module IntMap = Map.Make(Int) ;;

, dbm, bdb, sqlite,...

+7
let table : (int,string) Hashtbl.t = Hashtbl.create 8192
+5

To save the table in a separate file (for example, as an array), simply create a file strings.mlwith the contents:

let tbl = [|
    "String 0";
    "String 1";
    "String 2";
    ...7000 more...
|]

Compile this with:

ocamlc -c strings.ml

As explained in manual , this defines a module Stringsthat can be referenced by other Ocaml modules. For example, you can run a top-level file:

ocaml strings.cmo

And find the line by accessing a specific position in the array:

Strings.tbl.(1234) ;;
+4
source

All Articles