【问题标题】:Define map type in ocaml using the core library使用核心库在 ocaml 中定义地图类型
【发布时间】:2014-03-14 00:29:54
【问题描述】:

OCaml 语言的核心库带有非常有用的 Map 和 Table 模块。 如果我想使用某个内置类型的映射,我知道如何定义自己的类型:

type mytype = int String.Map.t (* A mapping from strings to integers *)

我也知道如何使用多态比较定义自定义地图:

type mytype = (string, string) Map.Poly.t (* A map from strings to strings *)

我不知道如何使用非多态比较来定义自定义映射,从我自己的类型到我自己的类型。 例如。假设我有

type row_t = Row of int
type column_t = Column of int
(* I want a map from rows to columns *)
type mymap_t = (row_t, column_t, ???) Map.t

我知道第三个参数应该是比较器,但我不知道在里面放什么:Int.comparator 和 Int.comparator_witness 都没有给出想要的结果。

【问题讨论】:

标签: ocaml ocaml-core


【解决方案1】:

您可以参考 Ashish 提到的博文。

但是,在使用 Core 时,我通常更喜欢更“自动”的方式来为自定义结构生成 Maps 和 Sets(感谢 Core 语法扩展)。

这是一个小例子:

module T = struct
  type t = Row of int
  with sexp, compare
end
include T
include Comparable.Make(T)

所以这将生成您通常需要的所有比较函数(和其他有用的函数)和基本数据结构:

type t = T.t = Row of int
...
val (>) : T.t -> T.t -> bool = <fun>    (* compare functions *)
val (<) : T.t -> T.t -> bool = <fun>
val equal : T.t -> T.t -> bool = <fun>
val compare : T.t -> T.t -> int = <fun>
val min : T.t -> T.t -> T.t = <fun>
val max : T.t -> T.t -> T.t = <fun>
...
module Map :  (* non-polymorphic Map module *)
...
end
module Set :  (* non-polymorphic Set module *)
...
end

还有更多。所以基本上你可以在之后使用非多态映射:

type column_t = Column of int
let map = Map.singleton (Row 1) (Column 2)

【讨论】:

  • 哇,谢谢!看到Comparable.Make(T) 实际上创建了Set、Map 和其他一系列,而不仅仅是比较器,这真是令人惊讶。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多