Exercise: Exceptions

The lecture on Monads and monad transformers introduced a transformer for handling failures, based on returning an element of the Maybe type

data Maybe a = Just a | Nothing

with Nothing indicating that a failure occurred.

This transformer is very suitable for applications such as parsing, where one explores many alternatives, and a failure just means that a different alternative should be explored. It is less useful when failures are unexpected, and we want to know why each failure occurred.

Another possibility is to use the standard type

data Either a b = Left a | Right b

to distinguish between a successful and a failing result. Let us adopt the convention that

Construct a monad transformer

newtype Exception e m a = Exception (m (Either e a))

by analogy with the Failure transformer. Follow the programme outlined in the lecture, and define also instances StateMonad (Exception e m) s and ExceptionMonad (State s m) e, so that State and Exception can be combined.