2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[PrelST]{The @ST@ monad}
7 {-# OPTIONS -fno-implicit-prelude #-}
14 import PrelNum () -- So that we get the .hi file for system imports
19 %*********************************************************
21 \subsection{The @ST@ monad}
23 %*********************************************************
25 The state-transformer monad proper. By default the monad is strict;
26 too many people got bitten by space leaks when it was lazy.
29 newtype ST s a = ST (STRep s a)
30 type STRep s a = State# s -> (# State# s, a #)
32 instance Functor (ST s) where
33 fmap f (ST m) = ST $ \ s ->
34 case (m s) of { (# new_s, r #) ->
37 instance Monad (ST s) where
41 return x = ST $ \ s -> (# s, x #)
42 m >> k = m >>= \ _ -> k
46 case (m s) of { (# new_s, r #) ->
47 case (k r) of { ST k2 ->
50 data STret s a = STret (State# s) a
52 -- liftST is useful when we want a lifted result from an ST computation. See
54 liftST :: ST s a -> State# s -> STret s a
55 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
57 {-# NOINLINE unsafeInterleaveST #-}
58 unsafeInterleaveST :: ST s a -> ST s a
59 unsafeInterleaveST (ST m) = ST ( \ s ->
61 r = case m s of (# _, res #) -> res
66 instance Show (ST s a) where
67 showsPrec _ _ = showString "<<ST action>>"
68 showList = showList__ (showsPrec 0)
74 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
78 (a, s') = newArray# 100 [] s
79 (_, s'') = fill_in_array_or_something a x s'
83 If we inline @runST@, we'll get:
86 (a, s') = newArray# 100 [] realWorld#{-NB-}
87 (_, s'') = fill_in_array_or_something a x s'
91 And now the @newArray#@ binding can be floated to become a CAF, which
92 is totally and utterly wrong:
95 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
98 let (_, s'') = fill_in_array_or_something a x s' in
101 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
105 -- The INLINE prevents runSTRep getting inlined in *this* module
106 -- so that it is still visible when runST is inlined in an importing
107 -- module. Regrettably delicate. runST is behaving like a wrapper.
108 runST :: (forall s. ST s a) -> a
109 runST st = runSTRep (case st of { ST st_rep -> st_rep })
111 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
112 -- That's what the "INLINE 100" says.
114 {-# INLINE 100 runSTRep #-}
115 runSTRep :: (forall s. STRep s a) -> a
116 runSTRep st_rep = case st_rep realWorld# of