2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1997
5 \section[LazyST]{The Lazy State Transformer Monad, @LazyST@}
7 This module presents an identical interface to ST, but the underlying
8 implementation of the state thread is lazy.
17 -- ST is one, so you'll likely need some Monad bits
21 newSTRef, readSTRef, writeSTRef,
24 newSTArray, readSTArray, writeSTArray, boundsSTArray,
25 thawSTArray, freezeSTArray, unsafeFreezeSTArray,
28 strictToLazyST, lazyToStrictST
32 import qualified STBase
34 import qualified Unsafe ( unsafeInterleaveST )
35 import PrelBase ( Eq(..), Int, Bool, ($), ()(..) )
39 newtype ST s a = ST (STBase.State s -> (a,STBase.State s))
41 instance Monad (ST s) where
43 return a = ST $ \ s -> (a,s)
44 m >> k = m >>= \ _ -> k
55 %*********************************************************
57 \subsection{Variables}
59 %*********************************************************
62 newSTRef :: a -> ST s (ST.STRef s a)
63 readSTRef :: ST.STRef s a -> ST s a
64 writeSTRef :: ST.STRef s a -> a -> ST s ()
66 newSTRef = strictToLazyST . ST.newSTRef
67 readSTRef = strictToLazyST . ST.readSTRef
68 writeSTRef r a = strictToLazyST (ST.writeSTRef r a)
71 %*********************************************************
75 %*********************************************************
78 newtype STArray s ix elt = STArray (MutableArray s ix elt)
80 newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
81 readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt
82 writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
83 boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix)
84 thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
85 freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
86 unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
89 strictToLazyST (newArray ixs init) >>= \arr ->
92 readSTArray (STArray arr) ix = strictToLazyST (readArray arr ix)
93 writeSTArray (STArray arr) ix v = strictToLazyST (writeArray arr ix v)
94 boundsSTArray (STArray arr) = boundsOfArray arr
96 strictToLazyST (thawArray arr) >>= \arr ->
98 freezeSTArray (STArray arr) = strictToLazyST (freezeArray arr)
99 unsafeFreezeSTArray (STArray arr) = strictToLazyST (unsafeFreezeArray arr)
101 strictToLazyST :: STBase.ST s a -> ST s a
102 strictToLazyST (STBase.ST m) = ST $ \s ->
103 let STBase.S# s# = s in
104 case m s# of { STBase.STret s2# r -> (r, STBase.S# s2#) }
106 lazyToStrictST :: ST s a -> STBase.ST s a
107 lazyToStrictST (ST m) = STBase.ST $ \s ->
108 case (m (STBase.S# s)) of (a, STBase.S# s') -> STBase.STret s' a
110 unsafeInterleaveST :: ST s a -> ST s a
111 unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST