OCaml 中的查找表

发布于 2024-07-13 10:29:39 字数 145 浏览 5 评论 0原文

我想在 OCaml 中创建一个查找表。 该表将包含 7000 多个条目,在查找(通过 int)时,返回一个字符串。 用于此任务的合适数据结构是什么? 该表是否应该从基本代码中外部化,如果是这样,如何“包括”可从他/她的程序访问的查找表?

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迷离° 2024-07-20 10:29:39

如果使用连续整数对字符串进行寻址,则可以使用数组。

否则,您可以使用哈希表(非功能性)或映射(功能性)。 要开始使用地图,请尝试:

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

module IntMap = Map.Make(Int) ;;

如果表太大而无法存储在内存中,您可以将其存储在外部数据库中并使用到 dbm,bdb,sqlite,...

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

清醇 2024-07-20 10:29:39
let table : (int,string) Hashtbl.t = Hashtbl.create 8192
let table : (int,string) Hashtbl.t = Hashtbl.create 8192
笙痞 2024-07-20 10:29:39

要将表存储在单独的文件中(例如作为数组),只需创建一个包含以下内容的文件 strings.ml

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

编译此文件:

ocamlc -c strings.ml

manual,这定义了其他 Ocaml 模块可以使用的模块 Strings参考。 例如,您可以启动一个顶层:

ocaml strings.cmo

并通过访问数组中的特定位置来查找字符串:

Strings.tbl.(1234) ;;

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) ;;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文