Topics in Advanced Computing Lesson 11: Monoids, Foldables, Monads

  1. Last time
    1. Functions
    2. Functions are applicative
  2. Finishing up
  3. Monads

Last time

Functions

Functions are functors! What would fmap mean here?

First some notation:

instance Functor ((->) r) where
  fmap f g = \x -> f (g x)

Or, more simply:

instance Functor ((->) r) where
  fmap f g = (.)

(Mathematically, functions are generalizations of sequences. A sequence of a’s is a function from [0..n] to a. If a sequence of a’s can be thought of as a functor, so should a list of a’s)

Functions are applicative

instance Applicative ((->) r) where
  pure x = (\_ -> x)
  f <*> g = \x -> f x (g x)

Example: What should the following output? (+) <$> (+5) <*> (*10) $ 2

Try to chase down what happens. (+) <$> (+5) <*> (*10) is the same as fmap (+) (+5) <*> (*10).

Finishing up

Can we implement the Tree foldable?

Monads

Functors: if we have a box of as, and a map from a -> b, can we get a box of bs?

Applicative functors: what if the map a -> b is also in the box?

Monads: if we have a box of as, and a function from a to a box of bs, then return a box of bs?

Example: looking up something in a table could return a Maybe.

class Applicative m => Monad m where
  (>>=) :: m a -> (a -> m b) -> m b
  (>>) :: m a -> m b -> m b
  return :: a -> m a
  {-# MINIMAL (>>=) #-}

>>= is the “bind” operator. >> is defined in terms of >>=, and return is, essentially, pure.

How would we implement this for a Maybe?

instance Monad Maybe where
  return = Just
  Nothing >>= _ = Nothing
  Just x >>= f = f x

Exercise: Consider the lookup function in the Data.Map module: lookup :: Ord k => k -> Map.Map k a -> Maybe a.

Suppose we want to do a kind of “triple lookup”: we call lookup on some key k, and if it’s Nothing, return Nothing, but if it’s Just x, then lookup x, and again, if it’s Nothing, return Nothing, otherwise if it’s Just y, return lookup y. How would we implement this? Is it possible that the Monad instance could help?

lookup3 :: Ord k => k -> Map.Map k k -> Maybe k
lookup3 k1 m = _ -- what goes here?

Reminder: what’s the syntax for >>=? It’s something like Maybe x >>= f, where f is a function that produces a Maybe.

Coming up: