Haskell/Solutions/Foldable

Deconstructing
1.

The class
1.

A summary of the answers. Subtle issues are explained in the notes just below.

Notes:

[i]: The monoid here is of type. The function  (defined as   in ) is needed to convert the inner values of the actions to , thereby discarding the inner values. This conversion is not needed with an implementation in terms of  (as the actual one is); however, for a   that isn't the generic one using , we would need to either discard the results using   (as done above) or create a wrapper which forgets the result type. The latter trick (a rather advanced one, in fact) uses a feature called existential quantification, and might look like this:

While this is a stylish solution, it creates a host of complications − we can't use  nor records, and we still need one   for extracting the final action. So take this approach merely as a curio.

On a more reasonable note,  only differs from   in the type signature, as   and. That also mean the observations above apply to it as well.

[ii]:  evaluates to the largest of its two arguments, and   is similar but involves. The usage of  here is just a trick to add an extra value of   to the type   so that   can become a legal. , as, is the identity of  , and hence acts as a value that is less than or equal to all values in   (e.g. something like negative infinity for the integers). This monoid may be implemented with the wrapper  as follows (and in fact something like this is used internally in the default implementation of   from ). Note that  cannot be used as , since  , and therefore   is not the identity of   as required by the monoid laws.

[iii]: By "leftmost ", we mean:

The mirrored alternative would be:

They are implemented through the  and     wrappers from  respectively.

[iv]: That is a condensed version of the solution to the  exercise in Higher-order functions. is a  wrapper which  s the   of a wrapped.

List-like folding
1a.

1b.

It is impossible to implement  using. Folding a tree like a list destroys information about the structure of the branches. That can be clearly displayed by finding a pair of trees with different structures but which are converted to equal lists by.

More facts about
1a.

1b.

1c.