我正在尝试通过列表来实现集合。这是实现的代码(我省略了接口(interface)):
module MySet : Set =
struct
type 'a set = 'a list
let empty : 'a set = []
let add (x: 'a) (s: 'a set) : 'a set =
if not(List.mem x s) then x::s
let remove (x: 'a) (s: 'a set) : 'a set =
let rec foo s res =
match s with
| [] -> List.rev res
| y::ys when y = x -> foo ys res
| y::ys -> foo ys (y::res)
in foo s []
let list_to_set (l: 'a list) : 'a set =
let rec foo l res =
match l with
| [] -> List.rev res
| x::xs when member x xs -> foo xs res
| x::xs -> foo xs (x::res)
in foo l []
let member (x: 'a) (s: 'set) : bool =
List.mem x s
let elements (s: 'a set) : 'a list =
let rec foo s res =
match s with
| [] -> List.rev res
| x::xs -> foo xs (x::res)
in foo s []
end;;
这是我得到的错误
Characters 162-164:
if not(List.mem x s) then x::s
^^
Error: The variant type unit has no constructor ::
我无法理解错误
最佳答案
自 4.01 以来我们收到了一个非常令人困惑的消息,它源于这样一个事实,即您没有 else 分支并且 () 是 unit
的有效构造函数.
因为你没有其他分支整个if
必须输入 unit
因此 then
也分支,它试图统一 then
中的表达式值为 unit
类型的分支并检测到 ::
不是 unit
类型值的构造函数.
你想写的是:
if not (List.mem x s) then x :: s else s
没有 else
分支你的add
函数需要输入 'a -> 'a set -> unit
奇怪的错误消息正在 OCaml 的问题跟踪器中进行错误跟踪,请参阅 PR 6173 .
关于OCaml:变体类型单元没有构造函数::,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22052471/