I was looking at the type annotation of function elem
. It looked like this:
elem :: Eq a => a -> t a -> Bool
I understand that Eq a =>
is a type constraint.
So a
must support ==
.
But I don't understand t a
, where does this t
came from ?
What does it do? Why is it necessary?
Link: https://hackage.haskell.org/package/base-4.16.0.0/docs/Prelude.html#v:elem
CodePudding user response:
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
.