Function rem1 :: Eq a => [a] -> a -> [a], that removes the elem mentioned in the second argument from the first argument

Viewed 168

I need to make a function that removes the first occurrence of an element, given in the second argument, from the list given as the first argument.

The print should for example look like this:

rem1 "abab" 'a' == "bab"
rem1 "abab" 'b' == "aab"
rem1 "abab" 'c' == "abab"

Completely new to Haskell and not sure where to begin. Any helpers? :)

Edit: This is what I have now, and it gives me "variable not in scope"

rem1 :: Eq a => [a] -> a -> [a]
rem1 [] _ = []
rem1 (x:xs) y 
    | x == y     = xs
    | otherwise  = x : rem1 xs y
1 Answers

You can use explicit recursion here. There are basically three cases here:

  1. the list is empty, in which case we did not find an element, then we can return the empty list;
  2. the list is not empty, and the first element matches the element we search for, in that case we return the rest of the elements; and
  3. the list is not empty and the first element does not match the element we are looking for. In that case we yield the first element, and we recurse on the rest of the list.

The "skeleton" of the function thus looks like:

rem1 :: Eq a => [a] -> a -> [a]
rem1 [] _ = …        -- (1)
rem1 (x:xs) y
    | x == y = …     -- (2)
    | otherwise = …  -- (3)

where you still need to fill in the … parts based on the corresponding description.

Related