简体   繁体   中英

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:

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:

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM