OCaml `Map.Make` 输入模块

OCaml `Map.Make` input module

我正在效仿here

module IntPairs =
struct
  type t = int * int
  let compare (x0,y0) (x1,y1) =
    match Stdlib.compare x0 x1 with
    | 0 -> Stdlib.compare y0 y1
    | c -> c
end

module PairsMap = Map.Make(IntPairs)

let m = PairsMap.(
  empty 
  |> add (0,1) "hello" 
  |> add (1,0) "world"
)

我的问题是,当我将 : Map.OrderedType 添加到 module IntPairs 定义时,为什么代码无法编译?像这样:

module IntPairs : Map.OrderedType =
struct
  type t = int * int
  let compare (x0,y0) (x1,y1) =
    match Stdlib.compare x0 x1 with
    | 0 -> Stdlib.compare y0 y1
    | c -> c
end

module PairsMap = Map.Make(IntPairs)

let m = PairsMap.(
  empty 
  |> add (0,1) "hello" 
  |> add (1,0) "world"
)

错误信息:

64 | let m = PairsMap.(empty |> add (0, 1) "hello" |> add (1, 0) "world")
                                    ^^^^^^
Error: This expression has type 'a * 'b
       but an expression was expected of type 
       key

难道IntPairs不应该实现模块类型Map.OrderedType吗?

当您指定类型时 Map.OrderedType 您将键的类型抽象化。相反,请尝试以下操作,您会发现您的代码有效。

module IntPairs : Map.OrderedType with type t = int * int =
struct
  type t = int * int
  let compare (x0,y0) (x1,y1) =
    match Stdlib.compare x0 x1 with
    | 0 -> Stdlib.compare y0 y1
    | c -> c
end

添加一组括号可能会消除语法歧义。

module IntPairs : (Map.OrderedType with type t = int * int) =
...