Haskell elem function definition has t a can you explain that

Viewed 188
1 Answers

The t is a Foldable typeclass, since it is defined in the Foldable class, so the signature is:

elem :: (Foldable t, Eq a) => a -> t a -> Bool

elem thus not only works on a list (where t ~ []), but on any Foldable, so t ~ Maybe, t ~ NonEmpty, t ~ Tree, etc. Its default implementation is [src]:

elem :: Eq a => a -> t a -> Bool
elem = any . (==)

It thus checks if any element of the Foldable is equal to the query element.

This thus means that it can also work for a Maybe a for example where Nothing can be seen as an empty collection, and Just x as a collection with one element: x, or for example look if the element is one of the values in a rose tree Tree a.

Related