Tutorial by Examples

length counts the occurences of elements a in a foldable structure t a. ghci> length [7, 2, 9] -- t ~ [] 3 ghci> length (Right 'a') -- t ~ Either e 1 -- 'Either e a' may contain zero or one 'a' ghci> length (Left "foo") -- t ~ Either String 0 ghci> length (3, True) ...
Any fold can be run in the opposite direction with the help of the Dual monoid, which flips an existing monoid so that aggregation goes backwards. newtype Dual a = Dual { getDual :: a } instance Monoid m => Monoid (Dual m) where mempty = Dual mempty (Dual x) `mappend` (Dual y) = Dua...
To instantiate Foldable you need to provide a definition for at least foldMap or foldr. data Tree a = Leaf | Node (Tree a) a (Tree a) instance Foldable Tree where foldMap f Leaf = mempty foldMap f (Node l x r) = foldMap f l `mappend` f x `mappend` foldMap f r fo...
toList flattens a Foldable structure t a into a list of as. ghci> toList [7, 2, 9] -- t ~ [] [7, 2, 9] ghci> toList (Right 'a') -- t ~ Either e "a" ghci> toList (Left "foo") -- t ~ Either String [] ghci> toList (3, True) -- t ~ (,) Int [True] toList is ...
traverse_ executes an Applicative action for every element in a Foldable structure. It ignores the action's result, keeping only the side-effects. (For a version which doesn't discard results, use Traversable.) -- using the Writer applicative functor (and the Sum monoid) ghci> runWriter $ trave...
foldMap maps each element of the Foldable structure to a Monoid, and then combines them into a single value. foldMap and foldr can be defined in terms of one another, which means that instances of Foldable need only give a definition for one of them. class Foldable t where foldMap :: Monoid m...
class Foldable t where {-# MINIMAL foldMap | foldr #-} foldMap :: Monoid m => (a -> m) -> t a -> m foldMap f = foldr (mappend . f) mempty foldr :: (a -> b -> b) -> b -> t a -> b foldr f z t = appEndo (foldMap (Endo #. f) t) z -- and a nu...
null returns True if there are no elements a in a foldable structure t a, and False if there is one or more. Structures for which null is True have a length of 0. ghci> null [] True ghci> null [14, 29] False ghci> null Nothing True ghci> null (Right 'a') False ghci> null ('x'...

Page 1 of 1