Kevin D
Kevin D

Reputation: 29

Why does the guarded statements not run?

Hello I'm in a programming languages class which we were just introduced to Haskell. So in the homework we had to create a function that can remove multiple instances of an element in a list. I had a previous function that can remove one element but my removeMultipleElements does not want to run the guarded statements and just go straight to the empty list. Any help is appreciated. I'm sure it is something syntactical but I'm not sure what.

Here is the code

--This one works great    
removeElement x aList@(y:ys)
        | y == x = rest
        | otherwise = y : rest
          where
            rest = removeElement x ys 
    removeElement _ _ = []

--this does not want to
removeMultipleElements remove@(y:ys) aList@(x:xs) 
        | elem y aList = removeMultipleElements ys (removeElement y aList)
        | not (elem y aList) = removeMultipleElements ys aList
        | otherwise = aList
removeMultipleElements _ _ = []

Upvotes: 0

Views: 77

Answers (1)

Philip JF
Philip JF

Reputation: 28539

The problem isn't the guard, it is that

removeMultipleElements remove@(y:ys) aList@(x:xs) 

will only match when neither list is empty, so in your base case you have

removeMultipleElements [] aList

which matches only with the second definition and so becomes the empty list. You should probably replace

removeMultipleElements _ _ = []

with something like

removeMultipleElements _ xs = xs

Upvotes: 3

Related Questions