OCaml `Map.Make` 输入模块

标签 ocaml

我正在按照示例 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) =
...

关于OCaml `Map.Make` 输入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72369715/

相关文章:

ocaml - ocaml 中阶乘函数的命令式版本有什么问题?

ocaml - 访问 Ocaml 中的记录字段

ocaml - 哪个 .cma 文件对应 OCaml 中的哪个模块?

ocaml - 删除列表中的前 n 个项目

haskell - Haskell 和 OCaml 中的仿函数有何相似之处?

emacs - OCaml Emacs Tuareg : Evaluate phrase keyboard shortcut, 以及如何显示实际的希腊符号?

ocaml - 如何隐藏构造函数?

c - If then 具有多个表达式 OCaml

header - 调用 OCaml 编译器来生成 .cmi

Ubuntu Ocaml llvm 未绑定(bind)模块 ExecutionEngine