playground/haskell/unsorted/state-monad.hs

30 lines
666 B
Haskell

-- | https://en.wikibooks.org/wiki/Haskell/Understanding_monads/State#Turnstile_Example
import Control.Monad
-- import Control.Monad.State -- For [state]
newtype State s a = State {
-- a 'state processor'
runState :: s -> (a, s)
-- | | |
-- initial state | |
-- 'output value' |
-- Final state
}
state :: (s -> (a, s)) -> State s a
state = State
instance Functor (State s) where
fmap = liftM
instance Applicative (State s) where
pure = return
(<*>) = ap
instance Monad (State s) where
return :: a -> State s a
return x = state (\s -> (x, s))
(>>=) :: State s a -> (a -> State s b) -> State s b