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.
18 -- ST is one, so you'll likely need some Monad bits
22 newSTRef, readSTRef, writeSTRef,
25 newSTArray, readSTArray, writeSTArray, boundsSTArray,
26 thawSTArray, freezeSTArray, unsafeFreezeSTArray,
29 strictToLazyST, lazyToStrictST
33 import qualified PrelST
35 import PrelBase ( Eq(..), Int, Bool, ($), ()(..) )
40 newtype ST s a = ST (PrelST.State s -> (a,PrelST.State s))
42 instance Monad (ST s) where
44 return a = ST $ \ s -> (a,s)
45 m >> k = m >>= \ _ -> k
55 -- ToDo: un-inline this, it could cause problems...
56 runST :: (All s => ST s a) -> a
57 runST st = case st of ST st -> let (r,_) = st (PrelST.S# realWorld#) in r
60 %*********************************************************
62 \subsection{Variables}
64 %*********************************************************
67 newSTRef :: a -> ST s (ST.STRef s a)
68 readSTRef :: ST.STRef s a -> ST s a
69 writeSTRef :: ST.STRef s a -> a -> ST s ()
71 newSTRef = strictToLazyST . ST.newSTRef
72 readSTRef = strictToLazyST . ST.readSTRef
73 writeSTRef r a = strictToLazyST (ST.writeSTRef r a)
76 %*********************************************************
80 %*********************************************************
83 newtype STArray s ix elt = STArray (MutableArray s ix elt)
85 newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
86 readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt
87 writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
88 boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix)
89 thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
90 freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
91 unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
94 strictToLazyST (newArray ixs init) >>= \arr ->
97 readSTArray (STArray arr) ix = strictToLazyST (readArray arr ix)
98 writeSTArray (STArray arr) ix v = strictToLazyST (writeArray arr ix v)
99 boundsSTArray (STArray arr) = boundsOfArray arr
101 strictToLazyST (thawArray arr) >>= \arr ->
103 freezeSTArray (STArray arr) = strictToLazyST (freezeArray arr)
104 unsafeFreezeSTArray (STArray arr) = strictToLazyST (unsafeFreezeArray arr)
106 strictToLazyST :: PrelST.ST s a -> ST s a
107 strictToLazyST (PrelST.ST m) = ST $ \s ->
110 PrelST.STret s2# r = m s#
114 lazyToStrictST :: ST s a -> PrelST.ST s a
115 lazyToStrictST (ST m) = PrelST.ST $ \s ->
116 case (m (PrelST.S# s)) of (a, PrelST.S# s') -> PrelST.STret s' a
118 unsafeInterleaveST :: ST s a -> ST s a
119 unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST