patternMinor
Implementing Haskell's `delete`
Viewed 0 times
implementinghaskelldelete
Problem
Learn You a Haskell shows the
delete: deletes first occurrence of item
Please critique my implementation.
I don't like the fact that I'm using the
Also, I don't know how to capture the first pattern match of
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.Solution
I think you're overcomplicating this a bit. Something like
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:
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 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 xsCode Snippets
delete' :: (Eq a) => a -> [a] -> [a]
delete' y [] = []delete' y (x:xs) = if x == y then xs else x : delete' y xsContext
StackExchange Code Review Q#49779, answer score: 5
Revisions (0)
No revisions yet.