summaryrefslogtreecommitdiff
path: root/compiler/GHC/Utils/Monad/State/Strict.hs
blob: d5298955a555db27d0c5fd9073e539354145a66c (plain)
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE PatternSynonyms #-}

-- | A state monad which is strict in its state.
module GHC.Utils.Monad.State.Strict
  ( -- * The State monad
    State(State)
  , state
  , evalState
  , execState
  , runState
    -- * Operations
  , get
  , gets
  , put
  , modify
  ) where

import GHC.Prelude

import GHC.Exts (oneShot)

-- | A state monad which is strict in the state.
newtype State s a = State' { runState' :: s -> (# a, s #) }
    deriving (Functor)

pattern State :: (s -> (# a, s #))
              -> State s a

-- This pattern synonym makes the monad eta-expand,
-- which as a very beneficial effect on compiler performance
-- See #18202.
-- See Note [The one-shot state monad trick] in GHC.Utils.Monad
pattern State m <- State' m
  where
    State m = State' (oneShot $ \s -> m s)

instance Applicative (State s) where
   pure x   = State $ \(!s) -> (# x, s #)
   m <*> n  = State $ \s -> case runState' m s of
                            (# f, !s' #) -> case runState' n s' of
                                            (# x, !s'' #) -> (# f x, s'' #)

instance Monad (State s) where
    m >>= n  = State $ \s -> case runState' m s of
                             (# r, !s' #) -> runState' (n r) s'

state :: (s -> (a, s)) -> State s a
state f = State $ \s -> case f s of
                        (r, !s') -> (# r, s' #)

get :: State s s
get = State $ \(!s) -> (# s, s #)

gets :: (s -> a) -> State s a
gets f = State $ \(!s) -> (# f s, s #)

put :: s -> State s ()
put !s' = State $ \_ -> (# (), s' #)

modify :: (s -> s) -> State s ()
modify f = State $ \s -> let !s' = f s in (# (), s' #)


evalState :: State s a -> s -> a
evalState s i = case runState' s i of
                (# a, _ #) -> a


execState :: State s a -> s -> s
execState s i = case runState' s i of
                (# _, s' #) -> s'


runState :: State s a -> s -> (a, s)
runState s i = case runState' s i of
               (# a, !s' #) -> (a, s')