2 {-# OPTIONS -fno-implicit-prelude #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) The University of Glasgow, 1992-2002
7 -- License : see libraries/base/LICENSE
9 -- Maintainer : cvs-ghc@haskell.org
10 -- Stability : internal
11 -- Portability : non-portable (GHC Extensions)
15 -----------------------------------------------------------------------------
26 %*********************************************************
28 \subsection{The @ST@ monad}
30 %*********************************************************
32 The state-transformer monad proper. By default the monad is strict;
33 too many people got bitten by space leaks when it was lazy.
36 newtype ST s a = ST (STRep s a)
37 type STRep s a = State# s -> (# State# s, a #)
39 instance Functor (ST s) where
40 fmap f (ST m) = ST $ \ s ->
41 case (m s) of { (# new_s, r #) ->
44 instance Monad (ST s) where
48 return x = ST (\ s -> (# s, x #))
49 m >> k = m >>= \ _ -> k
53 case (m s) of { (# new_s, r #) ->
54 case (k r) of { ST k2 ->
57 data STret s a = STret (State# s) a
59 -- liftST is useful when we want a lifted result from an ST computation. See
61 liftST :: ST s a -> State# s -> STret s a
62 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
64 {-# NOINLINE unsafeInterleaveST #-}
65 unsafeInterleaveST :: ST s a -> ST s a
66 unsafeInterleaveST (ST m) = ST ( \ s ->
68 r = case m s of (# _, res #) -> res
73 fixST :: (a -> ST s a) -> ST s a
75 let ans = liftST (k r) s
78 case ans of STret s' x -> (# s', x #)
80 instance Show (ST s a) where
81 showsPrec _ _ = showString "<<ST action>>"
82 showList = showList__ (showsPrec 0)
88 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
92 (a, s') = newArray# 100 [] s
93 (_, s'') = fill_in_array_or_something a x s'
97 If we inline @runST@, we'll get:
100 (a, s') = newArray# 100 [] realWorld#{-NB-}
101 (_, s'') = fill_in_array_or_something a x s'
105 And now the @newArray#@ binding can be floated to become a CAF, which
106 is totally and utterly wrong:
109 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
112 let (_, s'') = fill_in_array_or_something a x s' in
115 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
119 -- The INLINE prevents runSTRep getting inlined in *this* module
120 -- so that it is still visible when runST is inlined in an importing
121 -- module. Regrettably delicate. runST is behaving like a wrapper.
122 runST :: (forall s. ST s a) -> a
123 runST st = runSTRep (case st of { ST st_rep -> st_rep })
125 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
126 -- That's what the "INLINE [0]" says.
128 {-# INLINE [0] runSTRep #-}
129 runSTRep :: (forall s. STRep s a) -> a
130 runSTRep st_rep = case st_rep realWorld# of