[project @ 1997-03-14 05:24:14 by sof]
[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 (
10
11         -- ToDo: review this interface; I'm avoiding gratuitous changes for now
12         --                      SLPJ Jan 97
13
14
15         ST,
16
17         -- ST is one, so you'll likely need some Monad bits
18         module Monad,
19
20         thenST, seqST, returnST, listST, fixST, runST, unsafeInterleaveST,
21         mapST, mapAndUnzipST,
22
23         MutableVar,
24         newVar, readVar, writeVar, sameVar,
25
26         MutableArray,
27         newArray, readArray, writeArray, sameMutableArray
28
29     ) where
30
31 import IOBase   ( error )       -- [Source not needed]
32 import ArrBase
33 import STBase
34 import PrelBase ( Int, Bool, ($), ()(..) )
35 import GHC      ( newArray#, readArray#, writeArray#, sameMutableArray#, sameMutableByteArray# )
36 import Monad
37
38 \end{code}
39
40 %*********************************************************
41 %*                                                      *
42 \subsection{Variables}
43 %*                                                      *
44 %*********************************************************
45
46 \begin{code}
47 -- in ArrBase: type MutableVar s a = MutableArray s Int a
48
49 newVar   :: a -> ST s (MutableVar s a)
50 readVar  :: MutableVar s a -> ST s a
51 writeVar :: MutableVar s a -> a -> ST s ()
52 sameVar  :: MutableVar s a -> MutableVar s a -> Bool
53
54 newVar init = ST $ \ (S# s#) ->
55     case (newArray# 1# init s#)     of { StateAndMutableArray# s2# arr# ->
56     (MutableArray vAR_IXS arr#, S# s2#) }
57   where
58     vAR_IXS = error "newVar: Shouldn't access `bounds' of a MutableVar\n"
59
60 readVar (MutableArray _ var#) = ST $ \ (S# s#) ->
61     case readArray# var# 0# s#  of { StateAndPtr# s2# r ->
62     (r, S# s2#) }
63
64 writeVar (MutableArray _ var#) val = ST $ \ (S# s#) ->
65     case writeArray# var# 0# val s# of { s2# ->
66     ((), S# s2#) }
67
68 sameVar (MutableArray _ var1#) (MutableArray _ var2#)
69   = sameMutableArray# var1# var2#
70 \end{code}
71
72
73 \begin{code}
74 sameMutableArray     :: MutableArray s ix elt -> MutableArray s ix elt -> Bool
75 sameMutableByteArray :: MutableByteArray s ix -> MutableByteArray s ix -> Bool
76
77 sameMutableArray (MutableArray _ arr1#) (MutableArray _ arr2#)
78   = sameMutableArray# arr1# arr2#
79
80 sameMutableByteArray (MutableByteArray _ arr1#) (MutableByteArray _ arr2#)
81   = sameMutableByteArray# arr1# arr2#
82 \end{code}
83