Page 1

Monads

Sweeping computational details under the carpet in a systematic way

Page 2

Pure functional programming

Page 3

Functions in other languages

Functions can be pure, like in Haskell

Page 4
Functions in other languages

Functions can have additional inputs

Page 5
Functions in other languages

Functions can have additional outputs

Page 6
Functions in other languages

Functions can change the state and do IO

Page 7
Functions in other languages

Functions might not always return a result

Page 8

Functions with additional effects in Haskell

Page 9

Combining functions with additional effects

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

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

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

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

The burden of dealing with extra effects

Page 13

Function application with effects (1a)

Example: Extra output

Page 14

Function application with effects (1b)

Example: Extra output

Page 15

Function application with effects (2)

Page 16

Types for functions with effects (1)

Page 17

Types for functions with effects (2)

Page 18

Monads and monadic programming

Page 19

The Monad class

Page 20

The do notation

Page 21

Instances in the Monad class

Monads we have encountered before

instance Monad IO     -- predefined
instance Monad Gen    -- from QuickCheck
instance Monad Parser -- from the Parsing module
Page 22

The Maybe type is a monad

Page 23

The list type is a monad

Page 24

Combining monadic functions

Page 25

The Functor class

Page 26

Instances in the Functor class

Page 27

The Maybe type is a Functor

Page 28

The list type is a Functor

Page 29

The Applicative class

Page 30

Instances in the Applicative class

Page 31

The list type is in Applicative

Page 32

The Maybe type is in Applicative

Page 33

When is Applicative useful?

Do notation vs Applicative

Page 34

A note about changes in GHC 7.10