Haskell - how to check if an element is in a list using Foldr?

Viewed 384

I want to check whether a element is in a list, and I want to implement it using Foldr. I know it is wrong, but I can't get any further than the code below

func :: Eq a => a -> [a] -> Bool
func a b = foldr (==) a b

I furthermore got the first line of code from the lectures, but I don't really understand why Eq a is necessary and what it does.

1 Answers

If you want to check if an element a is in a list you need to compare it to each element in the list. Thus whatever type a is, it needs to implement Eq.

With :t foldr in e.g. ghci, you can see the type signature your inner function which I will call f needs:

foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

If you use (==) for f it does not work because you can only compare a list element to a Bool which should ultimately indicate whether a is in the list. So you need to figure out how to get a, the element you want to test for into f.

Related