isMember:: a -> [a] -> Bool
isMember y [] = False
isMember y (x:xs) =
if y == x then
True
else
isMember y xs
Trying to create a function that will identify whether something is a member of a list. For example:
isMember 6 [1,2,3,4,5,6]
>True
However I keep getting a complier error stating 'no instance for (Eq a) arising from the use of '=='
Help would be appreciated (I'm new to Haskell & Recursion in functional languages so explain like I'm five.)
you are almost there
isMember :: Eq a => a -> [a] -> Bool
isMember _ [] = False
isMember y (x:xs) =
if y == x then True else isMember y xs
What the compiler tells you that you promised to accept any type of list members - but later you use the function ==
which is not available for all types (for example functions).
By adding Eq a =>
you say I accept all input which have an equals method.
You can (re)write the last line as
isMember y (x:xs) = (y == x) || isMember y xs
which is equivalent to your implementation (thanks @chi for the comment). What is nice about your version is that it is tail recursive.
Another point to note - the pattern:
isMember _ [] = False
)isMember y (x:xs) = ...
)happens to turn up a lot and has been abstracted into the family of fold
-functions (foldl
, foldr
...). Putting it in your use case it looks like
isMember y xs = foldl False (\x b -> (x == y) || b) xs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With