Skip to content

Instantly share code, notes, and snippets.

@PiotrJander PiotrJander/State.hs
Created Jul 14, 2019

Embed
What would you like to do?
{-# LANGUAGE InstanceSigs #-}
newtype State s a = State { runState :: s -> (s, a) }
instance Functor (State s) where
fmap :: (a -> b) -> State s a -> State s b
fmap f ma = State (fmap f . runState ma)
instance Applicative (State s) where
pure :: a -> State s a
pure x = State (\st -> (st, x))
(<*>) :: (State s (a -> b)) -> State s a -> State s b
mf <*> ma = State (\st ->
let
(st', f) = runState mf st
(st'', x) = runState ma st'
in
(st'', f x)
)
instance Monad (State s) where
return :: a -> State s a
return = pure
(>>=) :: State s a -> (a -> State s b) -> State s b
ma >>= f = State (\st ->
let
(st', x) = runState ma st
(st'', y) = runState (f x) st'
in
(st'', y)
)
get :: State s s
get = State (\st -> (st, st))
put :: s -> State s ()
put st = State (\st' -> (st, ()))
puts :: (s -> s) -> State s ()
puts f = do
st <- get
put (f st)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.