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 Functor (ST s) where
50 instance Monad (ST s) where
52 return a = ST $ \ s -> (a,s)
53 m >> k = m >>= \ _ -> k
63 {-# NOINLINE runST #-}
64 runST :: (All s => ST s a) -> a
65 runST st = case st of ST st -> let (r,_) = st (PrelST.S# realWorld#) in r
68 %*********************************************************
70 \subsection{Variables}
72 %*********************************************************
75 newSTRef :: a -> ST s (ST.STRef s a)
76 readSTRef :: ST.STRef s a -> ST s a
77 writeSTRef :: ST.STRef s a -> a -> ST s ()
79 newSTRef = strictToLazyST . ST.newSTRef
80 readSTRef = strictToLazyST . ST.readSTRef
81 writeSTRef r a = strictToLazyST (ST.writeSTRef r a)
84 %*********************************************************
88 %*********************************************************
91 newtype STArray s ix elt = STArray (MutableArray s ix elt)
93 newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
94 readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt
95 writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
96 boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix)
97 thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
98 freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
99 unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
101 newSTArray ixs init =
102 strictToLazyST (newArray ixs init) >>= \arr ->
105 readSTArray (STArray arr) ix = strictToLazyST (readArray arr ix)
106 writeSTArray (STArray arr) ix v = strictToLazyST (writeArray arr ix v)
107 boundsSTArray (STArray arr) = boundsOfArray arr
109 strictToLazyST (thawArray arr) >>= \arr ->
111 freezeSTArray (STArray arr) = strictToLazyST (freezeArray arr)
112 unsafeFreezeSTArray (STArray arr) = strictToLazyST (unsafeFreezeArray arr)
114 strictToLazyST :: PrelST.ST s a -> ST s a
115 strictToLazyST (PrelST.ST m) = ST $ \s ->
117 pr = case s of { PrelST.S# s# -> m s# }
118 r = case pr of { PrelST.STret s2# r -> r }
119 s' = case pr of { PrelST.STret s2# r -> PrelST.S# s2# }
123 lazyToStrictST :: ST s a -> PrelST.ST s a
124 lazyToStrictST (ST m) = PrelST.ST $ \s ->
125 case (m (PrelST.S# s)) of (a, PrelST.S# s') -> PrelST.STret s' a
127 unsafeInterleaveST :: ST s a -> ST s a
128 unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST