2018-12-03 17:56
Page 1

Monads

Sweeping computational details under the carpet in a systematic way

Page 2

Reflections on last week's lecture

We wrote a parser for arithmetic expressions

Page 3

Pure functional programming

Page 4

Functions in other languages

Functions can be pure, like in Haskell

Page 5
Functions in other languages

Functions can have additional inputs

Page 6
Functions in other languages

Functions can have additional outputs

Page 7
Functions in other languages

Functions can change the state and do IO

Page 8
Functions in other languages

Functions might not always return a result

Page 9

Functions with additional effects in Haskell

Page 10

Combining functions with additional effects

Page 11
Combining functions with additional effects
 -- Extra output:      Input -> (Extra,Output)
h x = (o1<>o2,y2)
  where
    (o1,y1) = f x
    (o2,y2) = g y1

-- Changing the state: Input -> State -> (State,Output)
h x s0 = (s2,y2)
  where
     (s1,y1) = f x s0
     (s2,y2) = g y1 s1
Page 12
Combining functions with additional effects
 -- IO operations:      Input -> IO Output
h x = do y1 <- f x
         y2 <- g y1
         return y2

-- Sometimes no result: Input -> Maybe Output
h x = case f x of
        Nothing -> Nothing
        Just y -> g y

-- Many results:
h x = [y2 | y1 <- f x, y2 <- g y1]
Page 13

The burden of dealing with extra effects

Page 14

Function application with effects (1a)

Example: Extra output

Page 15

Function application with effects (1b)

Example: Extra output

Page 16

Function application with effects (2)

Page 17

Types for functions with effects (1)

Page 18

Types for functions with effects (2)

Page 19

Monads and monadic programming

Page 20

The Monad class

Page 21

The do notation

  • ‹m1 >>= (\x -> do y <- m2 x; return (x+y))›  ⟹ 
  • ‹m1 >>= (\x -> m2 x >>= (\y -> return (x+y)))›
    Page 22

    Combining monadic functions

    Page 23

    Type classes relating to monads

    f <$> x = fmap f x
    f =<< m = m >>= f
    Page 24

    The Functor class

    Page 25

    Functor vs the do notation

    Page 26

    The Applicative class

    Page 27

    Applicative vs the do notation

    Page 28

    Monadic Expression Evaluation

    Page 29

    Final thoughts on the monadic evaluator

    Page 30

    Further reading