3
votes

I'm trying to implement the elem function recursively. This is what I wrote:

 member :: Eq a => a -> [a] -> Bool
 member _ [] = False

 member n (x:xs)
     | n == x           = True : member (n xs)
     | otherwise        = False

 main = do
 print (member 10 [1,12,11])

I got a 'couldn't match expected type 'Bool' with actual type '[a0]' error.

I attempted the same using if..else..then as well, but in vain.

I think I'm missing out on a very basic and fundamental concept of Haskell here.

Help?

This and this didn't help me.

2

2 Answers

10
votes

The clause True : member (n xs) does not match with member's declared return type Bool. If you find an x in xs with x == n, then you want to simply return True.

Otherwise, you should recurse in member with a smaller list xs (i.e., check again for equality of n with the next element). Here is your code with these two problems fixed as described:

member n (x:xs) | n == x    = True
                | otherwise = member n xs
4
votes
  • If you have found the element, the answer is True. You seem to be trying to create a list there, not sure why...
  • If you haven't found it, recurse and check the tail...