14. Foldables and friends Flashcards

1
Q

What is a Monoid?

A

A set together with an associative operator that combines 2 elements from the set, and an identity element for the operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are Monoids used for?

A

As a way to define algebraic structures and provide a way to reason about and manipulate values of that structure

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give the declaration of a Monoid

A

class Monoid a where
mempty :: a
mappend :: a -> a -> a
mconcat :: [a] -> a
mconcat = foldr mappend mempty

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Give the 3 rules of the Monoid class

A
  1. mempty ‘mappend’ x = x
  2. x ‘mappend’ mempty = x
  3. x ‘mappend’ (y ‘mappend’ z) = (x ‘mappend’ y) ‘mappend’ z
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a Foldable?

A

A way to fold a data structure to a single value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the foldable declaration

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a Traversable?

A

A typeclass that defines a way to traverse a data structure, performing some operation on each element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Give the Traversable definition

A

class (Functor t, Foldable t) => Traversable t where
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

describe the sequenceA function and an example

A

sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id

> sequenceA [Just 1, Just 2, Just 3]
Just [1,2,3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly