tags:

views:

311

answers:

3

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.

+4  A: 
let table : (int,string) Hashtbl.t = Hashtbl.create 8192
Chris Conway
+5  A: 

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,...

Bruno De Fraine
If stored in an array (the index IS significant) but in a separate .ml file, how would I could about "including" the file that only contains the look-up table/array?
Mat
Please see my other answer.
Bruno De Fraine
+3  A: 

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) ;;
Bruno De Fraine
With this logic I've created two files: foo.ml and bar.ml. bar.ml contains the line "let x = [|3;2;1|];;" and foo.ml contains "open bar;; " which seems to incur a compiler error after running ocamlc -c bar.ml then ocamlc -o foo foo.ml . What's wrong here?
Mat
Do `open Bar;;`: module names start with a capital. `ocamlc` without `-c` also does linking: you provide all files that need to be linked in: `ocamlc -o foo bar.cmo foo.ml`
Bruno De Fraine