1 % ------------------------------------------------------------------------------
2 % $Id: PrelST.lhs,v 1.20 2001/02/22 16:48:24 qrczak Exp $
4 % (c) The University of Glasgow, 1992-2000
7 \section[PrelST]{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 instance Show (ST s a) where
69 showsPrec _ _ = showString "<<ST action>>"
70 showList = showList__ (showsPrec 0)
76 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
80 (a, s') = newArray# 100 [] s
81 (_, s'') = fill_in_array_or_something a x s'
85 If we inline @runST@, we'll get:
88 (a, s') = newArray# 100 [] realWorld#{-NB-}
89 (_, s'') = fill_in_array_or_something a x s'
93 And now the @newArray#@ binding can be floated to become a CAF, which
94 is totally and utterly wrong:
97 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
100 let (_, s'') = fill_in_array_or_something a x s' in
103 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
107 -- The INLINE prevents runSTRep getting inlined in *this* module
108 -- so that it is still visible when runST is inlined in an importing
109 -- module. Regrettably delicate. runST is behaving like a wrapper.
110 runST :: (forall s. ST s a) -> a
111 runST st = runSTRep (case st of { ST st_rep -> st_rep })
113 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
114 -- That's what the "INLINE 100" says.
116 {-# INLINE 100 runSTRep #-}
117 runSTRep :: (forall s. STRep s a) -> a
118 runSTRep st_rep = case st_rep realWorld# of