The Monad Challenges

A set of challenges for jump starting your understanding of monads.

Outline

Set 1: Random Numbers

Set 2: Failing Computations

Set 3: Combinations

Set 4: Common Abstraction

Set 5: Do Notation

This project is maintained by mightybyte

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Do Notation – operators

In the last exercise, we noted that the following code:

rule1 = do
    foo <- calcFoo
    bar foo

Is automatically de-sugared to:

rule1 = bind calcFoo (\foo -> bar foo)

In Haskell, the bind function is conventionally written as the >>= operator, which can be written infix style like this:

rule1 = calcFoo >>= (\foo -> bar foo)

In order for the do syntax to work correctly, we need to change our Monad class to have a >>= operator. Create a class like this:

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

    fail :: String -> m a
    fail = undefined

(Note: for historical reasons, Monad is required to have a fail function. We will not be concerning ourselves with failure here, so we just leave this as undefined. When you implement Monad for your own data types, you should only implement the >>= and return functions)

In the next few sections, we will be rewriting the earlier exercises using do syntax.

Previous Page - Next Page