8e2d68a5c840ef9f21e5a82a8832c0399a5c4406
[ghc-hetmet.git] / compiler / utils / State.hs
1 {-# OPTIONS_GHC -w #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 --     http://hackage.haskell.org/trac/ghc/wiki/WorkingConventions#Warnings
6 -- for details
7
8 module State where
9
10 newtype State s a
11         = State
12         { runState' :: s -> (# a, s #) }
13
14 instance Monad (State s) where
15     return x    = State $ \s -> (# x, s #)
16     m >>= n     = State $ \s ->
17                         case runState' m s of
18                           (# r, s' #)   -> runState' (n r) s'
19
20 get ::  State s s
21 get     = State $ \s -> (# s, s #)
22
23 gets :: (s -> a) -> State s a
24 gets f  = State $ \s -> (# f s, s #)
25
26 put ::  s -> State s ()
27 put s'  = State $ \s -> (# (), s' #)
28
29 modify :: (s -> s) -> State s ()
30 modify f = State $ \s -> (# (), f s #)
31
32
33 evalState :: State s a -> s -> a
34 evalState s i
35         = case runState' s i of
36                 (# a, s' #)     -> a
37
38
39 execState :: State s a -> s -> s
40 execState s i
41         = case runState' s i of
42                 (# a, s' #)     -> s'
43
44
45 runState :: State s a -> s -> (a, s)
46 runState s i
47         = case runState' s i of
48                 (# a, s' #)     -> (a, s')
49
50
51 mapAccumLM
52         :: Monad m
53         => (acc -> x -> m (acc, y))     -- ^ combining funcction
54         -> acc                          -- ^ initial state
55         -> [x]                          -- ^ inputs
56         -> m (acc, [y])                 -- ^ final state, outputs
57
58 mapAccumLM _ s []       = return (s, [])
59 mapAccumLM f s (x:xs)
60  = do
61         (s1, x')        <- f s x
62         (s2, xs')       <- mapAccumLM f s1 xs
63         return          (s2, x' : xs')