all and any
Just as we have foldMap
as a generalization of fold
, we can generalize and
and or
to
all :: Foldable t => (a -> Bool) -> t a -> Bool
any :: Foldable t => (a -> Bool) -> t a -> Bool
Instead of looking only at containers of Bool
s, we can take a container of
arbitrary a
s and a predicate pred
and ask whether all or at least one of the
elements in the container satisfy the predicate:
all, any :: Foldable t => (a -> Bool) -> t a -> Bool
all pred = getAll . foldMap (All . pred)
any pred = getAny . foldMap (Any . pred)
GHCi
>>> all even [1..10]
False
>>> any even [1..10]
True
>>> all even [2,4..10]
True
>>> any even [1,3..10]
False
Or for a tree as the container:
GHCi
>>> tree = Node Empty 5 (Node (Node Empty 3 Empty) 1 (Node Empty 2 Empty))
>>> any even tree
True
>>> all even tree
False
We could have defined and
and or
as specializations of all
and any
:
and = all id
or = any id
GHCi
>>> all id [True,False,True,True]
False
>>> all id [True,True,True,True]
True
>>> any id [True,False,False,False]
True
>>> any id [False,False,False,False]
False