OCaml:变体类型单元没有构造函数::

标签 ocaml

我正在尝试通过列表来实现集合。这是实现的代码(我省略了接口(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/

相关文章:

algorithm - OCaml 在列表中插入一个元素

inheritance - 包含模块继承的仿函数不起作用

ocaml - ` OCaml 中的运算符

syntax - 模块缩写

types - OCaml 在不相交的联合中有记录语法吗?

parsing - 使包含标记的表对 .mly 和 .mll 均可见(作者:menhir)

ocaml - Coq 中的非空列表追加定理

types - 无法理解 OCaml trie 类型声明

reference - 在 OCaml 中复制构造?

json - 如何更改 ppx_yojson_conv 表示变体的方式?