[project @ 1996-12-19 18:35:23 by simonpj]
[ghc-hetmet.git] / ghc / lib / glaExts / ST.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[module_ST]{The State Transformer Monad, @ST@}
5
6 \begin{code}
7 module ST where
8
9 import Prelude  ()
10 import IOBase   ( error )       -- [Source not needed]
11 import ArrBase
12 import STBase
13 import PrelBase ( Int, Bool, ($), ()(..) )
14 import GHC      ( newArray#, readArray#, writeArray#, sameMutableArray# )
15 \end{code}
16
17 %*********************************************************
18 %*                                                      *
19 \subsection{Variables}
20 %*                                                      *
21 %*********************************************************
22
23 \begin{code}
24 type MutableVar s a = MutableArray s Int a
25
26 newVar   :: a -> ST s (MutableVar s a)
27 readVar  :: MutableVar s a -> ST s a
28 writeVar :: MutableVar s a -> a -> ST s ()
29 sameVar  :: MutableVar s a -> MutableVar s a -> Bool
30
31 newVar init = ST $ \ (S# s#) ->
32     case (newArray# 1# init s#)     of { StateAndMutableArray# s2# arr# ->
33     (MutableArray vAR_IXS arr#, S# s2#) }
34   where
35     vAR_IXS = error "newVar: Shouldn't access `bounds' of a MutableVar\n"
36
37 readVar (MutableArray _ var#) = ST $ \ (S# s#) ->
38     case readArray# var# 0# s#  of { StateAndPtr# s2# r ->
39     (r, S# s2#) }
40
41 writeVar (MutableArray _ var#) val = ST $ \ (S# s#) ->
42     case writeArray# var# 0# val s# of { s2# ->
43     ((), S# s2#) }
44
45 sameVar (MutableArray _ var1#) (MutableArray _ var2#)
46   = sameMutableArray# var1# var2#
47 \end{code}
48
49
50
51 sameMutableArray     :: MutableArray s ix elt -> MutableArray s ix elt -> Bool
52 sameMutableByteArray :: MutableByteArray s ix -> MutableByteArray s ix -> Bool
53
54 sameMutableArray (MutableArray _ arr1#) (MutableArray _ arr2#)
55   = sameMutableArray# arr1# arr2#
56
57 sameMutableByteArray (MutableByteArray _ arr1#) (MutableByteArray _ arr2#)
58   = sameMutableByteArray# arr1# arr2#
59 \end{code}
60