Reputation: 65
I will have to create a recursive function called removeList.Can anyone help me?
Upvotes: 1
Views: 124
Reputation: 531165
makeList
is a regular function, not a data constructor, so you can't pattern match on it. You need to pattern match on Cons
and Nil
; the fact that the list was returned by makeList
isn't relevant.
removeList :: Eq a => a -> List a -> List a
removeList _ Nil = Nil
removeList x (Cons y ys) | x == y = ys -- Don't recurse if you only want to remove the *first* occurrence.
| otherwise = Cons y (removeList x ys)
You can work directly with your List
type; there is no need to build the result as a built-in list then convert it again.
Compare to the same function implemented on built-in lists, with the type constructor []
and the data constructor (:)
used in prefix position rather than infix position.
removeList' :: Eq a => a -> [] a -> [] a
removeList' _ [] = []
removeList' x ((:) y ys) | x == y = ys
| otherwise = (:) y (removeList' x ys)
Just for fun, let's generalize this code so that it can be used as the basis for both removeFirst
and removeAll
:
removeGeneric :: Eq a => (List a -> List a) -> a -> List a -> List a
removeGeneric _ _ Nil = Nil
removeGeneric f x (Cons y ys) | x == y = f y ys
| otherwise = Cons y (removeGeneric f x ys)
removeFirst = removeGeneric (\y ys -> ys)
removeAll = removeGeneric removeAll
The first argument to removeGeneric
is the function you call on the list the first time you find a match. To remove the first occurrence, you just call the equivalent of tail
. To remove all occurrences, you recurse.
Upvotes: 3