1 % ------------------------------------------------------------------------------
2 % $Id: PrelST.lhs,v 1.15 2000/06/30 13:39:36 simonmar Exp $
4 % (c) The University of Glasgow, 1992-2000
7 \section[PrelST]{The @ST@ monad}
10 {-# OPTIONS -fno-implicit-prelude #-}
17 import PrelNum () -- So that we get the .hi file for system imports
22 %*********************************************************
24 \subsection{The @ST@ monad}
26 %*********************************************************
28 The state-transformer monad proper. By default the monad is strict;
29 too many people got bitten by space leaks when it was lazy.
32 newtype ST s a = ST (STRep s a)
33 type STRep s a = State# s -> (# State# s, a #)
35 instance Functor (ST s) where
36 fmap f (ST m) = ST $ \ s ->
37 case (m s) of { (# new_s, r #) ->
40 instance Monad (ST s) where
44 return x = ST $ \ s -> (# s, x #)
45 m >> k = m >>= \ _ -> k
49 case (m s) of { (# new_s, r #) ->
50 case (k r) of { ST k2 ->
53 data STret s a = STret (State# s) a
55 -- liftST is useful when we want a lifted result from an ST computation. See
57 liftST :: ST s a -> State# s -> STret s a
58 liftST (ST m) = \s -> case m s of (# s', r #) -> STret s' r
60 {-# NOINLINE unsafeInterleaveST #-}
61 unsafeInterleaveST :: ST s a -> ST s a
62 unsafeInterleaveST (ST m) = ST ( \ s ->
64 r = case m s of (# _, res #) -> res
69 instance Show (ST s a) where
70 showsPrec _ _ = showString "<<ST action>>"
71 showList = showList__ (showsPrec 0)
77 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
81 (a, s') = newArray# 100 [] s
82 (_, s'') = fill_in_array_or_something a x s'
86 If we inline @runST@, we'll get:
89 (a, s') = newArray# 100 [] realWorld#{-NB-}
90 (_, s'') = fill_in_array_or_something a x s'
94 And now the @newArray#@ binding can be floated to become a CAF, which
95 is totally and utterly wrong:
98 (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
101 let (_, s'') = fill_in_array_or_something a x s' in
104 All calls to @f@ will share a {\em single} array! End SLPJ 95/04.
108 -- The INLINE prevents runSTRep getting inlined in *this* module
109 -- so that it is still visible when runST is inlined in an importing
110 -- module. Regrettably delicate. runST is behaving like a wrapper.
111 runST :: (forall s. ST s a) -> a
112 runST st = runSTRep (case st of { ST st_rep -> st_rep })
114 -- I'm only letting runSTRep be inlined right at the end, in particular *after* full laziness
115 -- That's what the "INLINE 100" says.
117 {-# INLINE 100 runSTRep #-}
118 runSTRep :: (forall s. STRep s a) -> a
119 runSTRep st_rep = case st_rep realWorld# of