Skip to main content

State Monad

Monad type class

class Monad m where
return :: a -> m a
(> > =) :: m a -> (a -> m b) -> m b
(> >) :: m a -> m b -> m b
x > > y = x > > = \_ -> y
fail :: String -> m a

Maybe Monad

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

State Monad

newtype State

instance Monad (State s) where
return x = State $ \s -> (x, s)
(State h) > > = f = State $ \s ->
let (a, newState) = h s
(State g) = f a
in g newState

newtype State s a = State { runState :: s -> (a, s) }

  • State s vs. State h
    -- State s: partial application
    -- State h: this is a value

  • type of f
    f: a -> m b

record syntax

ghci> data Person = Person { name:: String, age:: Int} deriving (Show)
ghci> :t name
name :: Person -> String
ghci> :t age
age :: Person -> Int
ghci>

name and age are field accessor, they are converted to functions automatically by Haskell