This is an old revision of the document!


Lab 10. Monads

A monad is an algebraic structure used to describe computations as sequences of steps, and to handle side effects such as state and IO. They also provide a clean way to structure our programs.

In Haskell, Monads are defined as follows:

class Monad m where 
  (>>=) :: m a -> (a -> m b) -> m b
  return :: a -> m a

Recalling from this week's lecture, we know they (“»=”) is the equivalent to our “join” operation which performs the sequencing. We also know that m is of kind * ⇒ *, hence is a container.

Click to display ⇲

Click to hide ⇱

We also recall that not all containers are monads and that all monads are functors.


Monads are already implemented in Haskell, 'Maybe' being one of them:

instance Monad Maybe where
  mx >>= f = 
      case mx of 
        Just v -> f v
        Nothing -> Nothing
 
  return = Just

Do not forget about the syntactic sugar presented at lecture!

This section is meant to accommodate you to using Monads by playing around with an already implemented and familiar Monad: Maybe. We will work with the Nat data type that you already should be familiar with. Add the following lines to your code:

data Nat = Zero | Succ Nat deriving Show
 
fromInt :: Int -> Maybe Nat 
fromInt x 
  | x < 0 = Nothing
  | otherwise = Just $ get x
      where get 0 = Zero
            get x = Succ (get (x-1))

Every exercise will require you to implement extra functions which process Nat numbers such as adding or subtracting. Use fromInt function to manually test your solutions.

10.1.1 Implement the following adding and subtracting functions. Using Maybe allows us to easily treat the case of negative numbers.

mminus :: Maybe Nat -> Maybe Nat -> Maybe Nat
mminus m n = ???
 
mplus :: Maybe Nat -> Maybe Nat -> Maybe Nat
mplus m n = ???

10.1.2 Implement multiplication (from scratch, do not use the already defined mplus).

mmulti :: Maybe Nat -> Maybe Nat -> Maybe Nat
mmulti m n = ???