嘿大家我正在尝试编写此代码,而我遇到的数据类型有问题
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.
感谢任何帮助 感谢
答案 0 :(得分:7)
第一个问题,在表达式中:
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)))