2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[PrelST]{The @ST@ monad}
7 {-# OPTIONS -fno-implicit-prelude #-}
15 import PrelNum () -- So that we get the .hi file for system imports
18 %*********************************************************
20 \subsection{The @ST@ monad}
22 %*********************************************************
24 The state-transformer monad proper. By default the monad is strict;
25 too many people got bitten by space leaks when it was lazy.
28 newtype ST s a = ST (STRep s a)
29 type STRep s a = State# s -> (# State# s, a #)
31 instance Functor (ST s) where
32 fmap f (ST m) = ST $ \ s ->
33 case (m s) of { (# new_s, r #) ->
36 instance Monad (ST s) where
40 return x = ST $ \ s -> (# s, x #)
41 m >> k = m >>= \ _ -> k
45 case (m s) of { (# new_s, r #) ->
46 case (k r) of { ST k2 ->
49 data STret s a = STret (State# s) a
51 -- liftST is useful when we want a lifted result from an ST computation. See
53 liftST :: ST s a -> State# s -> STret s a
54 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
56 fixST :: (a -> ST s a) -> ST s a
58 let ans = liftST (k r) s
61 case ans of STret s' x -> (# s', x #)
63 {-# NOINLINE unsafeInterleaveST #-}
64 unsafeInterleaveST :: ST s a -> ST s a
65 unsafeInterleaveST (ST m) = ST ( \ s ->
67 r = case m s of (# _, res #) -> res
72 instance Show (ST s a) where
73 showsPrec _ _ = showString "<<ST action>>"
74 showList = showList__ (showsPrec 0)
80 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
84 (a, s') = newArray# 100 [] s
85 (_, s'') = fill_in_array_or_something a x s'
89 If we inline @runST@, we'll get:
92 (a, s') = newArray# 100 [] realWorld#{-NB-}
93 (_, s'') = fill_in_array_or_something a x s'
97 And now the @newArray#@ binding can be floated to become a CAF, which
98 is totally and utterly wrong:
101 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
104 let (_, s'') = fill_in_array_or_something a x s' in
107 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
111 -- The INLINE prevents runSTRep getting inlined in *this* module
112 -- so that it is still visible when runST is inlined in an importing
113 -- module. Regrettably delicate. runST is behaving like a wrapper.
114 runST :: (forall s. ST s a) -> a
115 runST st = runSTRep (case st of { ST st_rep -> st_rep })
117 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
118 -- That's what the "INLINE 100" says.
120 {-# INLINE 100 runSTRep #-}
121 runSTRep :: (forall s. STRep s a) -> a
122 runSTRep st_rep = case st_rep realWorld# of