使用核心库在ocaml中定义地图类型
问题描述:
OCaml语言的核心库附带非常有用的地图和表格模块。 我知道如何定义自己的类型,如果我想使用一些内置类型的地图:使用核心库在ocaml中定义地图类型
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
无法得到期望的结果。
答
你可以参考Ashish提到的博客文章。
但是在使用Core时,我通常更喜欢使用更多的“自动”方法来为自定义结构生成地图和集合(感谢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)
+0
哇,谢谢!看到Comparable.Make(T)实际上创建了Set,Map以及其他所有的系列,而不仅仅是比较器,真是令人惊讶。 –
不[本博客文章(https://ocaml.janestreet.com/?q=node/112)的帮助。 –