简体   繁体   English

另一个Haskell类型的困境

[英]Another haskell type dilemma

Hey everyone i am trying to write this code and I am having problems with the data types 大家好,我正在尝试编写此代码,但数据类型存在问题

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)

I am getting this error, its a problem with the types: 我收到此错误,它是类型的问题:

 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.

Any help is appreciated Thanks 任何帮助表示赞赏,谢谢

First problem, in the expression: 第一个问题,在表达式中:

Set ([x] : remove numberToRemove xs)

The head of the list (before : ) must be an Int, not a [Int], replace with: 列表的开头(在:之前)必须是Int,而不是[Int],并替换为:

Set (x : remove numberToRemove xs)

Then, a second problem. 然后,第二个问题。 In the same expression, the sub-expression: 在相同的表达式中,子表达式:

remove numberToRemove xs

is a Collecion, but there must be a [Int] after the operator : so, a possible solution: 是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