[project @ 1998-02-02 17:27:26 by simonm]
[ghc-hetmet.git] / ghc / lib / std / PrelUnsafeST.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4
5 \section[UnsafeST]{Module @UnsafeST@}
6
7 These functions have their own module because we definitely don't want
8 them to be inlined.
9
10 \begin{code}
11 {-# OPTIONS -fno-implicit-prelude #-}
12
13 module PrelUnsafeST (unsafeInterleaveST, runST) where
14
15 import PrelST
16 import PrelBase
17 \end{code}
18
19 \begin{code}
20 unsafeInterleaveST :: ST s a -> ST s a
21 unsafeInterleaveST (ST m) = ST ( \ s ->
22     let
23         STret _ r = m s
24     in
25     STret s r)
26
27 \end{code}
28
29 Definition of runST
30 ~~~~~~~~~~~~~~~~~~~
31
32 SLPJ 95/04: Why @runST@ must not have an unfolding; consider:
33 \begin{verbatim}
34 f x =
35   runST ( \ s -> let
36                     (a, s')  = newArray# 100 [] s
37                     (_, s'') = fill_in_array_or_something a x s'
38                   in
39                   freezeArray# a s'' )
40 \end{verbatim}
41 If we inline @runST@, we'll get:
42 \begin{verbatim}
43 f x = let
44         (a, s')  = newArray# 100 [] realWorld#{-NB-}
45         (_, s'') = fill_in_array_or_something a x s'
46       in
47       freezeArray# a s''
48 \end{verbatim}
49 And now the @newArray#@ binding can be floated to become a CAF, which
50 is totally and utterly wrong:
51 \begin{verbatim}
52 f = let
53     (a, s')  = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
54     in
55     \ x ->
56         let (_, s'') = fill_in_array_or_something a x s' in
57         freezeArray# a s''
58 \end{verbatim}
59 All calls to @f@ will share a {\em single} array!  End SLPJ 95/04.
60
61 \begin{code}
62 runST :: (All s => ST s a) -> a
63 runST st = 
64   case st of
65         ST m -> case m realWorld# of
66                         STret _ r -> r
67 \end{code}
68