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
20 %*********************************************************
22 \subsection{The @ST@ monad}
24 %*********************************************************
26 The state-transformer monad proper. By default the monad is strict;
27 too many people got bitten by space leaks when it was lazy.
30 newtype ST s a = ST (STRep s a)
31 type STRep s a = State# s -> (# State# s, a #)
33 instance Functor (ST s) where
34 fmap f (ST m) = ST $ \ s ->
35 case (m s) of { (# new_s, r #) ->
38 instance Monad (ST s) where
42 return x = ST $ \ s -> (# s, x #)
43 m >> k = m >>= \ _ -> k
47 case (m s) of { (# new_s, r #) ->
48 case (k r) of { ST k2 ->
51 data STret s a = STret (State# s) a
53 -- liftST is useful when we want a lifted result from an ST computation. See
55 liftST :: ST s a -> State# s -> STret s a
56 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
58 {-# NOINLINE unsafeInterleaveST #-}
59 unsafeInterleaveST :: ST s a -> ST s a
60 unsafeInterleaveST (ST m) = ST ( \ s ->
62 r = case m s of (# _, res #) -> res
67 instance Show (ST s a) where
68 showsPrec _ _ = showString "<<ST action>>"
69 showList = showList__ (showsPrec 0)
75 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
79 (a, s') = newArray# 100 [] s
80 (_, s'') = fill_in_array_or_something a x s'
84 If we inline @runST@, we'll get:
87 (a, s') = newArray# 100 [] realWorld#{-NB-}
88 (_, s'') = fill_in_array_or_something a x s'
92 And now the @newArray#@ binding can be floated to become a CAF, which
93 is totally and utterly wrong:
96 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
99 let (_, s'') = fill_in_array_or_something a x s' in
102 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
106 -- The INLINE prevents runSTRep getting inlined in *this* module
107 -- so that it is still visible when runST is inlined in an importing
108 -- module. Regrettably delicate. runST is behaving like a wrapper.
109 runST :: (forall s. ST s a) -> a
110 runST st = runSTRep (case st of { ST st_rep -> st_rep })
112 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
113 -- That's what the "INLINE 100" says.
115 {-# INLINE 100 runSTRep #-}
116 runSTRep :: (forall s. STRep s a) -> a
117 runSTRep st_rep = case st_rep realWorld# of