1 % ------------------------------------------------------------------------------
2 % $Id: ST.lhs,v 1.2 2001/12/21 15:07:25 simonmar Exp $
4 % (c) The University of Glasgow, 1992-2000
7 \section[GHC.ST]{The @ST@ monad}
10 {-# OPTIONS -fno-implicit-prelude #-}
21 %*********************************************************
23 \subsection{The @ST@ monad}
25 %*********************************************************
27 The state-transformer monad proper. By default the monad is strict;
28 too many people got bitten by space leaks when it was lazy.
31 newtype ST s a = ST (STRep s a)
32 type STRep s a = State# s -> (# State# s, a #)
34 instance Functor (ST s) where
35 fmap f (ST m) = ST $ \ s ->
36 case (m s) of { (# new_s, r #) ->
39 instance Monad (ST s) where
43 return x = ST $ \ s -> (# s, x #)
44 m >> k = m >>= \ _ -> k
48 case (m s) of { (# new_s, r #) ->
49 case (k r) of { ST k2 ->
52 data STret s a = STret (State# s) a
54 -- liftST is useful when we want a lifted result from an ST computation. See
56 liftST :: ST s a -> State# s -> STret s a
57 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
59 {-# NOINLINE unsafeInterleaveST #-}
60 unsafeInterleaveST :: ST s a -> ST s a
61 unsafeInterleaveST (ST m) = ST ( \ s ->
63 r = case m s of (# _, res #) -> res
68 fixST :: (a -> ST s a) -> ST s a
70 let ans = liftST (k r) s
73 case ans of STret s' x -> (# s', x #)
75 instance Show (ST s a) where
76 showsPrec _ _ = showString "<<ST action>>"
77 showList = showList__ (showsPrec 0)
83 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
87 (a, s') = newArray# 100 [] s
88 (_, s'') = fill_in_array_or_something a x s'
92 If we inline @runST@, we'll get:
95 (a, s') = newArray# 100 [] realWorld#{-NB-}
96 (_, s'') = fill_in_array_or_something a x s'
100 And now the @newArray#@ binding can be floated to become a CAF, which
101 is totally and utterly wrong:
104 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
107 let (_, s'') = fill_in_array_or_something a x s' in
110 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
114 -- The INLINE prevents runSTRep getting inlined in *this* module
115 -- so that it is still visible when runST is inlined in an importing
116 -- module. Regrettably delicate. runST is behaving like a wrapper.
117 runST :: (forall s. ST s a) -> a
118 runST st = runSTRep (case st of { ST st_rep -> st_rep })
120 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
121 -- That's what the "INLINE [0]" says.
123 {-# INLINE [0] runSTRep #-}
124 runSTRep :: (forall s. STRep s a) -> a
125 runSTRep st_rep = case st_rep realWorld# of