dc62000a217766763aa24bf0aac9f891cde9d82b
[ghc-base.git] / GHC / ST.lhs
1 \begin{code}
2 {-# LANGUAGE NoImplicitPrelude, MagicHash, UnboxedTuples, Rank2Types #-}
3 {-# OPTIONS_HADDOCK hide #-}
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module      :  GHC.ST
7 -- Copyright   :  (c) The University of Glasgow, 1992-2002
8 -- License     :  see libraries/base/LICENSE
9 -- 
10 -- Maintainer  :  cvs-ghc@haskell.org
11 -- Stability   :  internal
12 -- Portability :  non-portable (GHC Extensions)
13 --
14 -- The 'ST' Monad.
15 --
16 -----------------------------------------------------------------------------
17
18 -- #hide
19 module GHC.ST where
20
21 import GHC.Base
22 import GHC.Show
23
24 default ()
25 \end{code}
26
27 %*********************************************************
28 %*                                                      *
29 \subsection{The @ST@ monad}
30 %*                                                      *
31 %*********************************************************
32
33 The state-transformer monad proper.  By default the monad is strict;
34 too many people got bitten by space leaks when it was lazy.
35
36 \begin{code}
37 -- | The strict state-transformer monad.
38 -- A computation of type @'ST' s a@ transforms an internal state indexed
39 -- by @s@, and returns a value of type @a@.
40 -- The @s@ parameter is either
41 --
42 -- * an uninstantiated type variable (inside invocations of 'runST'), or
43 --
44 -- * 'RealWorld' (inside invocations of 'Control.Monad.ST.stToIO').
45 --
46 -- It serves to keep the internal states of different invocations
47 -- of 'runST' separate from each other and from invocations of
48 -- 'Control.Monad.ST.stToIO'.
49 --
50 -- The '>>=' and '>>' operations are strict in the state (though not in
51 -- values stored in the state).  For example,
52 --
53 -- @'runST' (writeSTRef _|_ v >>= f) = _|_@
54 newtype ST s a = ST (STRep s a)
55 type STRep s a = State# s -> (# State# s, a #)
56
57 instance Functor (ST s) where
58     fmap f (ST m) = ST $ \ s ->
59       case (m s) of { (# new_s, r #) ->
60       (# new_s, f r #) }
61
62 instance Monad (ST s) where
63     {-# INLINE return #-}
64     {-# INLINE (>>)   #-}
65     {-# INLINE (>>=)  #-}
66     return x = ST (\ s -> (# s, x #))
67     m >> k   = m >>= \ _ -> k
68
69     (ST m) >>= k
70       = ST (\ s ->
71         case (m s) of { (# new_s, r #) ->
72         case (k r) of { ST k2 ->
73         (k2 new_s) }})
74
75 data STret s a = STret (State# s) a
76
77 -- liftST is useful when we want a lifted result from an ST computation.  See
78 -- fixST below.
79 liftST :: ST s a -> State# s -> STret s a
80 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
81
82 {-# NOINLINE unsafeInterleaveST #-}
83 unsafeInterleaveST :: ST s a -> ST s a
84 unsafeInterleaveST (ST m) = ST ( \ s ->
85     let
86         r = case m s of (# _, res #) -> res
87     in
88     (# s, r #)
89   )
90
91 -- | Allow the result of a state transformer computation to be used (lazily)
92 -- inside the computation.
93 -- Note that if @f@ is strict, @'fixST' f = _|_@.
94 fixST :: (a -> ST s a) -> ST s a
95 fixST k = ST $ \ s ->
96     let ans       = liftST (k r) s
97         STret _ r = ans
98     in
99     case ans of STret s' x -> (# s', x #)
100
101 instance  Show (ST s a)  where
102     showsPrec _ _  = showString "<<ST action>>"
103     showList       = showList__ (showsPrec 0)
104 \end{code}
105
106 Definition of runST
107 ~~~~~~~~~~~~~~~~~~~
108
109 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
110 \begin{verbatim}
111 f x =
112   runST ( \ s -> let
113                     (a, s')  = newArray# 100 [] s
114                     (_, s'') = fill_in_array_or_something a x s'
115                   in
116                   freezeArray# a s'' )
117 \end{verbatim}
118 If we inline @runST@, we'll get:
119 \begin{verbatim}
120 f x = let
121         (a, s')  = newArray# 100 [] realWorld#{-NB-}
122         (_, s'') = fill_in_array_or_something a x s'
123       in
124       freezeArray# a s''
125 \end{verbatim}
126 And now the @newArray#@ binding can be floated to become a CAF, which
127 is totally and utterly wrong:
128 \begin{verbatim}
129 f = let
130     (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
131     in
132     \ x ->
133         let (_, s'') = fill_in_array_or_something a x s' in
134         freezeArray# a s''
135 \end{verbatim}
136 All calls to @f@ will share a {\em single} array!  End SLPJ 95/04.
137
138 \begin{code}
139 {-# INLINE runST #-}
140 -- The INLINE prevents runSTRep getting inlined in *this* module
141 -- so that it is still visible when runST is inlined in an importing
142 -- module.  Regrettably delicate.  runST is behaving like a wrapper.
143
144 -- | Return the value computed by a state transformer computation.
145 -- The @forall@ ensures that the internal state used by the 'ST'
146 -- computation is inaccessible to the rest of the program.
147 runST :: (forall s. ST s a) -> a
148 runST st = runSTRep (case st of { ST st_rep -> st_rep })
149
150 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
151 -- That's what the "INLINE [0]" says.
152 --              SLPJ Apr 99
153 -- {-# INLINE [0] runSTRep #-}
154
155 -- SDM: further to the above, inline phase 0 is run *before*
156 -- full-laziness at the moment, which means that the above comment is
157 -- invalid.  Inlining runSTRep doesn't make a huge amount of
158 -- difference, anyway.  Hence:
159
160 {-# NOINLINE runSTRep #-}
161 runSTRep :: (forall s. STRep s a) -> a
162 runSTRep st_rep = case st_rep realWorld# of
163                         (# _, r #) -> r
164 \end{code}