2014-02-14 24 views
1

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.comparatorInt.comparator_witness無法得到期望的結果。

+0

不[本博客文章(https://ocaml.janestreet.com/?q=node/112)的幫助。 –

回答

1

你可以參考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以及其他所有的系列,而不僅僅是比較器,真是令人驚訝。 –

相關問題