Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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