Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
http://chrisdone.com/posts/monads-are-burritos
Monad is an interface
Components
datatype and encapsulation
composable functions
monad laws
Actions
sequential (daisy) chaining
provides do notation
Can model imperative aspects of programming
Can combine pure and unpure code
Main part of the monad definition
Bind
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
*Pictures taken from very nice pictorial explanations of monads given in this blog post
Maybe/Option
Maybe type
as a monad
foo = do
filename <- getLine
contents <- readFile filename
putStrLn contents
Benefits of the interface
data Expr = Val Int | Div Expr Expr > eval (Div (Val 4) (Val 2))
2
we want to write
this evaluator
Benefits of the interface
data Expr = Val Int | Div Expr Expr > eval (Div (Val 1) (Val 0))
*** Exception: divide by zero
eval :: Expr -> Int
eval (Val n) = n
eval (Div x y) = eval x div eval y we want to
avoid this error
simple
implementation
Benefits of the interface
data Expr = Val Int | Div Expr Expr > eval (Div (Val 1) (Val 0))
*** Exception: divide by zero
eval :: Expr -> Int
eval (Val n) = n safediv :: Int -> Int -> Maybe Int
eval (Div x y) = eval x div eval y safediv _ 0 = Nothing
safediv n m = Just (n div m)
Pattern matching
might fail
do { action1 x1
; mk_action3 x1 x2 }
do { True <- action1 x1
; x2 <- action2 do { putString(Hello)
; action3 x1 x2 } putString(World)
return () }
Fail is called
action1 x1 >>= f >>
where similar to bind
f True = do { x2 <- action2; mk_action3 x1 x2 } but does not use value
f_ = fail "..." -- A compiler-generated message.
Monad laws
Left identity: return a >>= k =ka
Right identity:
m >>= return =m
which gives us
do { x <- return x; f x } do { f x }
Reader monad
State monad
Writer monad
Example of using writer monad
data Writer w a = Writer { runWriter :: (a, w) }