嘿大家我想写这个代码,我遇到了数据类型的问题
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)
Run Code Online (Sandbox Code Playgroud)
我收到此错误,它的类型有问题:
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.
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏谢谢
第一个问题,在表达式中:
Set ([x] : remove numberToRemove xs)
Run Code Online (Sandbox Code Playgroud)
列表的头部(在:之前)必须是Int,而不是[Int],替换为:
Set (x : remove numberToRemove xs)
Run Code Online (Sandbox Code Playgroud)
然后,第二个问题.在同一个表达式中,子表达式:
remove numberToRemove xs
Run Code Online (Sandbox Code Playgroud)
是一个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)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |