-- Counter.hs

module Counter where

data State s a = ST (s -> (a,s))   -- State : * -> * -> *

instance Monad (State s) where     -- State s : * -> *
  return x = ST(\s -> (x,s))
  (ST m) >>= f = ST(\s -> let (x,s') = m s
                              ST f' = f x
                            in f' s')

type Counter = State Int       -- Counter : * -> *

getCount :: Counter Int
getCount = ST(\n -> (n,n+1))

reset :: () -> Counter ()
reset () = ST(\n -> ((),0::Int))

run :: Int -> Counter a -> (a,Int)
run init (ST f) = let (x,s) = f init in (x,s)
