Question

I would like to create a lookup table in OCaml. The table will have 7000+ entries that, upon lookup (by int), return a string. What is an appropriate data structure to use for this task? Should the table be externalized from the base code and if so, how does one go about "including" the lookup table to be accessible from his/her program?

Thanks.

Was it helpful?

Solution

If the strings are addressed using consecutive integers you could 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) ;;

If the table is too large to store in memory, you could store it in an external database and use bindings to dbm, bdb, sqlite,...

OTHER TIPS

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

To store the table in a separate file (e.g. as an array), simply create a file strings.ml with the content:

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

Compile this with:

ocamlc -c strings.ml

As explained in the manual, this defines a module Strings that other Ocaml modules can reference. For example, you can start a toplevel:

ocaml strings.cmo

And lookup a string by accessing a particular position in the array:

Strings.tbl.(1234) ;;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top