The Monad Challenges

PureScript Edition

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

MCPrelude documentation

This project is maintained by shaunplee and is a fork of the Monad Challenges 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 PureScript, 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 and add an infix definition:

class Monad m where
    bind :: forall a b. m a -> (a -> m b) -> m b
    pure :: forall a. a -> m a

infix 1 bind as >>=

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

Previous Page - Next Page