Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
module StateMonadT where
-- Type representing a state transforming function
data StateT m s a = St { runSt :: s-> m (a, s) }
-- Functor instance
instance Functor m=> Functor (StateT m s) where
fmap f st1 = St $ \s-> fmap (\(a1, s1)-> (f a1, s1)) (runSt st1 s)
-- Applicate instance
instance Monad m=> Applicative (StateT m s) where
pure a = St $ \s-> return (a, s)
p <*> q = St $ \s-> do (f, s') <- runSt p s
(a, s'') <- runSt q s'
return (f a, s'')
-- Composition: Monad instance
instance Monad m=> Monad (StateT m s) where
f >>= g = St $ \s -> do (a, s') <- runSt f s
runSt (g a) s'
return a = St $ \s-> return (a, s)
-- Lifting
lift :: Monad m=> m a-> StateT m s a
lift ma = St $ \s-> do a<- ma; return (a, s)
-- Basic operations
-- Reading the state
get :: Monad m=> (s-> a)-> StateT m s a
get f = St $ \s-> return (f s, s)
-- Setting the state
set :: Monad m=> (s-> s)-> StateT m s ()
set g = St $ \s-> return ((), g s)