[project @ 1997-11-24 15:43:22 by simonm]
[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         ST,
12
13         runST,                          -- :: (All s => ST s a) -> a
14         fixST,                          -- :: (a -> ST s a) -> ST s a
15
16         unsafeInterleaveST,
17
18         -- ST is one, so you'll likely need some Monad bits
19         module Monad,
20
21         STRef,
22         newSTRef, readSTRef, writeSTRef,
23
24         STArray,
25         newSTArray, readSTArray, writeSTArray, Ix
26
27     ) where
28
29 import ArrBase
30 import Unsafe   ( unsafeInterleaveST )
31 import STBase
32 import PrelBase ( Eq(..), Int, Bool, ($), ()(..) )
33 import Monad
34 import Ix
35
36 \end{code}
37
38 %*********************************************************
39 %*                                                      *
40 \subsection{Variables}
41 %*                                                      *
42 %*********************************************************
43
44 \begin{code}
45 newtype STRef s a = STRef (MutableVar s a) 
46     deriving Eq
47
48 newSTRef :: a -> ST s (STRef s a)
49 newSTRef v = newVar v >>= \ var -> return (STRef var)
50
51 readSTRef :: STRef s a -> ST s a
52 readSTRef (STRef var) = readVar var
53
54 writeSTRef :: STRef s a -> a -> ST s ()
55 writeSTRef (STRef var) v = writeVar var v
56 \end{code}
57
58 %*********************************************************
59 %*                                                      *
60 \subsection{Arrays}
61 %*                                                      *
62 %*********************************************************
63
64 \begin{code}
65 newtype STArray s ix elt = STArray (MutableArray s ix elt)
66     deriving Eq
67
68 newSTArray              :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
69 writeSTArray            :: Ix ix => STArray s ix elt -> ix -> elt -> ST s () 
70 readSTArray             :: Ix ix => STArray s ix elt -> ix -> ST s elt 
71 boundsSTArray           :: Ix ix => STArray s ix elt -> (ix, ix)  
72 thawSTArray             :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
73 freezeSTArray           :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
74 unsafeFreezeSTArray     :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
75
76 newSTArray ixs elt = 
77     newArray ixs elt >>= \arr -> 
78     return (STArray arr)
79
80 boundsSTArray (STArray arr) = boundsOfArray arr
81
82 readSTArray (STArray arr) ix = readArray arr ix
83
84 writeSTArray (STArray arr) ix elt = writeArray arr ix elt
85
86 thawSTArray arr = thawArray arr >>= \starr -> return (STArray starr)
87
88 freezeSTArray (STArray arr) = freezeArray arr
89
90 unsafeFreezeSTArray (STArray arr) = unsafeFreezeArray arr
91 \end{code}
92