Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting an element of a set

im trying to delete an element from a set but I can’t seem to get the syntax right. The datatype is defined as follows:

data Menge el = Menge [el] deriving (Eq, Ord, Show)

and the function is:

loeschen :: (Ord el) => el -> Menge el -> Menge el
loeschen el (Menge []) = Menge []
loeschen el (Menge (x:xs))
    | el == x = Menge xs
    | otherwise = Menge (x : loeschen el (Menge xs))

The error says "Couldn’t match expected type: [el] with actual type: Menge el"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve tried several versions of the part after (x:) but I always get the same error.

Thanks in advance!

>Solution :

The problem is that your loeschen el (Menge xs) returns a Menge, so you can not use that with x : loeschen el (Menge xs), since that expects a list as second parameter.

You probably overcomplicate this however. You can just unwrap the list once, remove the item, and then add the result in a Menge, like:

loeschen :: Eq el => el -> Menge el -> Menge el
loeschen el (Menge xs) = Menge (go xs)
  where
    go [] = []
    go (x : xs)
      | el == x = xs
      | otherwise = x : go xs

removing an element from a list is however alread implemented with delete :: Eq a => a -> [a] -> [a], so we can implement this as:

import Data.List (delete)

loeschen :: Eq el => el -> Menge el -> Menge el
loeschen el (Menge xs) = Menge (delete el xs)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading