Learn You a Haskell shows the delete function.

delete: deletes first occurrence of item

ghci> delete 'h' "hey there ghang!"  
"ey there ghang!"

Please critique my implementation.

delete' :: (Eq a) => a -> [a] -> [a]
delete' y xs = delete'' y xs []
                 where delete'' _ [] _ = []
                       delete'' d (a:as) acc
                         | a == d    = reverse acc ++ as
                         | otherwise = delete'' d as (a:acc)

I don't like the fact that I'm using the : operator, but then calling reverse and acc ++ as.

Also, I don't know how to capture the first pattern match of delete'' with a single pattern match and guards alone.


1 Answer 1


I think you're overcomplicating this a bit. Something like delete certainly shouldn't need reverse or ++ to implement.

For the initial list, there are two cases - it either contains an element, or is empty. That much exists in your code. The empty case is simple, just return the empty list:

delete' :: (Eq a) => a -> [a] -> [a]
delete' y [] = []

Ok, so what about when the list is not empty. Well, in that case, we can simply think about it as follows: if the next element is equal to the element we want to remove, then remove it and return the rest of the list. Otherwise, append the next element and remove the first occurrence from the tail of the list. In code, this looks like:

delete' y (x:xs) = if x == y then xs else x : delete' y xs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.