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 {-# NOINLINE unsafeInterleaveST #-}
57 unsafeInterleaveST :: ST s a -> ST s a
58 unsafeInterleaveST (ST m) = ST ( \ s ->
60 r = case m s of (# _, res #) -> res
65 instance Show (ST s a) where
66 showsPrec _ _ = showString "<<ST action>>"
67 showList = showList__ (showsPrec 0)
73 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
77 (a, s') = newArray# 100 [] s
78 (_, s'') = fill_in_array_or_something a x s'
82 If we inline @runST@, we'll get:
85 (a, s') = newArray# 100 [] realWorld#{-NB-}
86 (_, s'') = fill_in_array_or_something a x s'
90 And now the @newArray#@ binding can be floated to become a CAF, which
91 is totally and utterly wrong:
94 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
97 let (_, s'') = fill_in_array_or_something a x s' in
100 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
104 -- The INLINE prevents runSTRep getting inlined in *this* module
105 -- so that it is still visible when runST is inlined in an importing
106 -- module. Regrettably delicate. runST is behaving like a wrapper.
107 runST :: (forall s. ST s a) -> a
108 runST st = runSTRep (case st of { ST st_rep -> st_rep })
110 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
111 -- That's what the "INLINE 100" says.
113 {-# INLINE 100 runSTRep #-}
114 runSTRep :: (forall s. STRep s a) -> a
115 runSTRep st_rep = case st_rep realWorld# of