| Prev: The monad laws | TOC: Contents | Next: Monad support in Haskell |
This section contains a few simple exercises to hone the reader's monadic reasoning skills and to provide a solid comprehension of the function and use of the Maybe and List monads before looking at monadic programming in more depth. The exercises will build on the previous sheep-cloning example, with which the reader should already be familiar.
Rewrite the maternalGrandfather,
fathersMaternalGrandmother, and
mothersPaternalGrandfather functions in Example 2
using the monadic operators return and >>=,
without using any do-notation syntactic sugar.
Click here to see the solution.
Write functions parent and grandparent with
signature Sheep -> Maybe Sheep. They
should return one sheep selected from all sheep matching the description, or
Nothing if there is no such sheep. Hint: the
mplus operator is useful here.
Click here to see the solution.
Write functions parent and grandparent with
signature Sheep -> [Sheep]. They
should return all sheep matching the description, or the empty list
if there is no such sheep. Hint: the mplus operator in the List
monad is useful here. Also the maybeToList function in
the Maybe module can be used to convert a value from the
Maybe monad to the List monad.
Click here to see the solution.
Monads promote modularity and code reuse by encapsulating often-used
computational strategies into single blocks of code that can be used
to construct many different computations. Less obviously, monads also
promote modularity by allowing you to vary the monad in which a
computation is done to achieve different variations of the computation.
This is achieved by writing functions which are polymorphic in the
monad type constructor, using the (Monad m) =>,
(MonadPlus m) =>, etc. class constraints.
Write functions parent and grandparent with
signature (MonadPlus m) => Sheep -> m Sheep. They
should be useful in both the Maybe and List monads. How does the
functions' behavior differ when used with the List monad versus the
Maybe monad? If you need to review the use of type classes and class
constraints in Haskell, look
here.
Click here to see the solution.
| Prev: The monad laws | TOC: Contents | Next: Monad support in Haskell |