我正在尝试通过列表实现集合..这是带有实现的代码(我省略了接口):
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;;
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误
Characters 162-164:
if not(List.mem x s) then x::s
^^
Error: The variant type unit has no constructor ::
Run Code Online (Sandbox Code Playgroud)
我无法理解错误
这是一个非常令人困惑的消息,我们从4.01开始就是因为你没有其他分支而且()是一个有效的构造函数unit.
由于你没有其他分支,所以if必须键入unit并因此then分支,并且它尝试then使用type值统一分支中的表达式unit并检测它::不是类型值的构造函数unit.
你想写的是:
if not (List.mem x s) then x :: s else s
Run Code Online (Sandbox Code Playgroud)
如果没有else分支,您的add函数需要键入'a -> 'a set -> unit
在OCaml的问题跟踪器中正在跟踪奇怪的错误消息,请参阅PR 6173.