14. Foldables and friends Flashcards
What is a Monoid?
A set together with an associative operator that combines 2 elements from the set, and an identity element for the operator.
What are Monoids used for?
As a way to define algebraic structures and provide a way to reason about and manipulate values of that structure
Give the declaration of a Monoid
class Monoid a where
mempty :: a
mappend :: a -> a -> a
mconcat :: [a] -> a
mconcat = foldr mappend mempty
Give the 3 rules of the Monoid class
- mempty ‘mappend’ x = x
- x ‘mappend’ mempty = x
- x ‘mappend’ (y ‘mappend’ z) = (x ‘mappend’ y) ‘mappend’ z
What is a Foldable?
A way to fold a data structure to a single value.
What is the foldable declaration
class Foldable t where
fold :: Monoid a => t a -> a
foldMap :: Monoid b => (a -> b) -> t a -> b
foldr :: (a -> b -> b) -> b -> t a -> b
foldl :: (a -> b -> a) -> a -> t b -> a
What is a Traversable?
A typeclass that defines a way to traverse a data structure, performing some operation on each element.
Give the Traversable definition
class (Functor t, Foldable t) => Traversable t where
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
describe the sequenceA function and an example
sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id
> sequenceA [Just 1, Just 2, Just 3]
Just [1,2,3]