gpt4 book ai didi

OCaml `Map.Make` 输入模块

转载 作者:行者123 更新时间:2023-12-05 02:29:02 25 4
gpt4 key购买 nike

我正在按照示例 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com