簡體   English   中英

另一個Haskell類型的困境

[英]Another haskell type dilemma

大家好,我正在嘗試編寫此代碼,但數據類型存在問題

data Collection = Set [Int] deriving (Show)

remove :: Int -> Collection -> Collection
remove _ (Set []) = (Set [])
remove numberToRemove (Set (x:xs))
    |x == numberToRemove = (Set xs)
    |otherwise = Set ([x]:remove numberToRemove xs)

我收到此錯誤,它是類型的問題:

 Couldn't match expected type `Int' with actual type `[t0]'
In the first argument of `(:)', namely `[x]'
In the first argument of `Set', namely
  `([x] : remove numberToRemove xs)'
In the expression: Set ([x] : remove numberToRemove xs)
Failed, modules loaded: none.

任何幫助表示贊賞,謝謝

第一個問題,在表達式中:

Set ([x] : remove numberToRemove xs)

列表的開頭(在:之前)必須是Int,而不是[Int],並替換為:

Set (x : remove numberToRemove xs)

然后,第二個問題。 在相同的表達式中,子表達式:

remove numberToRemove xs

是Collecion,但運算符后必須有[Int]:因此,可能的解決方案:

data Collection = Set [Int] deriving (Show)

col_to_list :: Collection -> [Int]
col_to_list (Set xs) = xs

remove :: Int -> Collection -> Collection
remove _ (Set []) = (Set [])
remove numberToRemove (Set (x:xs))
    |x == numberToRemove = (Set xs)
    |otherwise = Set (x : col_to_list (remove numberToRemove (Set xs)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM