简体   繁体   English

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

[英]OCaml: the variant type unit has no constructor ::

I'm trying to implement sets through lists.. This is the code with the implementation (I omitted the 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;;

This is the error I get 这是我得到的错误

Characters 162-164:
        if not(List.mem x s) then x::s 
                                   ^^
Error: The variant type unit has no constructor ::

I can't understand the error 我不明白这个错误

It's a very confusing message that we got since 4.01 that stems from the fact that you have no else branch and that () is a valid constructor for unit . 自4.01以来我们得到的消息非常混乱,这是由于您没有else分支,并且()是unit的有效构造函数。

Since you have no else branch the whole if must type to unit and thus the then branch aswell and it tries to unify the expression in the then branch with a value of type unit and detects that :: is not a constructor for values of type unit . 由于您没有else分支,因此整个if必须键入为unit ,因此then分支也将继续,它会尝试将then分支中的表达式与类型为unit的值统一,并检测::不是为unit类型的值的构造函数。

What you wanted to write is: 您要写的是:

if not (List.mem x s) then x :: s else s

Without an else branch your add function needs to type to 'a -> 'a set -> unit 没有else分支,您的add函数需要键入'a -> 'a set -> unit

The strange error message is being bug tracked in OCaml's issue tracker, see PR 6173 . 在OCaml的问题跟踪器中正在跟踪奇怪的错误消息,请参阅PR 6173

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM