[英]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.