on 413edee help sign in
40 lines 1.2 kB history raw
1module Control.Monad.State
3import Control.Monad.Identity
4import Prelude.Monad
5import Prelude.Functor
7%access public
9class Monad m => MonadState s (m : Type -> Type) where
10 get : m s
11 put : s -> m ()
13record StateT : Type -> (Type -> Type) -> Type -> Type where
14 ST : {m : Type -> Type} ->
15 (runStateT : s -> m (a, s)) -> StateT s m a
17instance Functor f => Functor (StateT s f) where
18 fmap f (ST g) = ST (\st => fmap (mapFst f) (g st)) where
19 mapFst : (a -> x) -> (a, b) -> (x, b)
20 mapFst fn (a, b) = (fn a, b)
22instance Monad f => Applicative (StateT s f) where
23 pure x = ST (\st => pure (x, st))
25 (ST f) <$> (ST a) = ST (\st => do (g, r) <- f st
26 (b, t) <- a r
27 return (g b, t))
29instance Monad m => Monad (StateT s m) where
30 (ST f) >>= k = ST (\st => do (v, st') <- f st
31 let ST kv = k v
32 kv st')
34instance Monad m => MonadState s (StateT s m) where
35 get = ST (\x => return (x, x))
36 put x = ST (\y => return ((), x))
38State : Type -> Type -> Type
39State s a = StateT s Identity a