Notes week of 5 Nov

  • Generalizing generators
  • always/andThen

type Gen s a = s -> (a,s)


Some of the types we’ve seen that involve generators…

The andThen may look confusing but take away the Gen s and it’s almost nothing:

This is like an inverse function application: argument first, then function, result.

Here is how the function would be defined with Gen s added back:

And how we’d use it to define something like threeRandoms

Wow — all the careful state-threading is now hidden! It is performed by andThen but here we can treat it as “behind the scenes.”

Here’s how we’d rewrite the tree-processing using andThen:

Haskell has a special syntax called “do” syntax for “Monads” which support these operations. Eventually we’d be able to turn this into:

Exercise? Many list operations could be defined to work on generators instead. For example, here’s the type of filter. Can you write filterGen?


The two monad operations:

return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b

The operator is called “bind”. Sometimes called “flatMap”, sometimes called “andThen”.

Maybe is a monad. Either is a monad (in the Right side). List is a monad. Gen is a monad.

Let’s define the two monad functions for Maybe.

Formula: 2a/b + (a-1)/(a+b)

Haskell has a “do” syntax for monads.

Or, generalizing the division so we can substitute any monad there:

ghci> formulaG safeDiv 3 4
Just 1.7857142857142856
ghci> formulaG (\i j -> [i,j]) 3 4
[8,13,6,11]