fe03258098e384fd997c18c1f06029dbf55d9fb7
[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 {-# OPTIONS -fno-implicit-prelude #-}
8
9 module ST where
10
11 import IOBase   ( error )       -- [Source not needed]
12 import ArrBase
13 import STBase
14 import PrelBase ( Int, Bool, ($), ()(..) )
15 import GHC      ( newArray#, readArray#, writeArray#, sameMutableArray# )
16 \end{code}
17
18 %*********************************************************
19 %*                                                      *
20 \subsection{Variables}
21 %*                                                      *
22 %*********************************************************
23
24 \begin{code}
25 type MutableVar s a = MutableArray s Int a
26
27 newVar   :: a -> ST s (MutableVar s a)
28 readVar  :: MutableVar s a -> ST s a
29 writeVar :: MutableVar s a -> a -> ST s ()
30 sameVar  :: MutableVar s a -> MutableVar s a -> Bool
31
32 newVar init = ST $ \ (S# s#) ->
33     case (newArray# 1# init s#)     of { StateAndMutableArray# s2# arr# ->
34     (MutableArray vAR_IXS arr#, S# s2#) }
35   where
36     vAR_IXS = error "newVar: Shouldn't access `bounds' of a MutableVar\n"
37
38 readVar (MutableArray _ var#) = ST $ \ (S# s#) ->
39     case readArray# var# 0# s#  of { StateAndPtr# s2# r ->
40     (r, S# s2#) }
41
42 writeVar (MutableArray _ var#) val = ST $ \ (S# s#) ->
43     case writeArray# var# 0# val s# of { s2# ->
44     ((), S# s2#) }
45
46 sameVar (MutableArray _ var1#) (MutableArray _ var2#)
47   = sameMutableArray# var1# var2#
48 \end{code}
49
50
51
52 sameMutableArray     :: MutableArray s ix elt -> MutableArray s ix elt -> Bool
53 sameMutableByteArray :: MutableByteArray s ix -> MutableByteArray s ix -> Bool
54
55 sameMutableArray (MutableArray _ arr1#) (MutableArray _ arr2#)
56   = sameMutableArray# arr1# arr2#
57
58 sameMutableByteArray (MutableByteArray _ arr1#) (MutableByteArray _ arr2#)
59   = sameMutableByteArray# arr1# arr2#
60 \end{code}
61