2014-02-26 58 views
2

我試圖通過列表來實現套。這與執行的代碼(我省略接口):OCaml的:變量類型單位沒有構造函數::

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 :: 

我無法理解的錯誤

回答

5

這是因爲4.01是一個事實,即你沒有else分支和(莖,我們得到了一個非常混亂的消息)是一個有效的構造函數unit

既然你沒有else分支整個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

相關問題