Skip to main content

7. Monads II

27/02/23

(>>=) - Sequencing ... General time of the bind operator

do -

Formal defenition of Monads

class Applicative m => Monad m where
(>>=) :: m a -> (a->m b) -> m b

return - used for class theory. Also used when handling monads in do

Example - Maybe

instance Monad Maybe where
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= f = Nothing
Just x >>= f = f x

Example - Lists

instance Monad [] where
-- (>>=) :: [a] -> (a -> [b]) -> [b]
xs >>= f = concat (map f xs)
-- = [y | x <- xs, y <- f x] (alternative)

Example - State

Most important monad in the course

Can have any types of State

type State = ..
type ST a = State -> (a, State)

Can use newtype for a single constructor.

Making ST into the monad state

instance Monad ST where
-- return :: a -> ST a
return x = S(\s -> (?,?))
-- (>>=) :: ST a -> (a -> ST b) -> ST b
st >>= f = S(\s ->
let (x,s') = app st s
in app(f x) s')