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, Ix,
26 strictToLazyST, lazyToStrictST
30 import qualified STBase
32 import Unsafe ( unsafeInterleaveST )
33 import PrelBase ( Eq(..), Int, Bool, ($), ()(..) )
37 newtype ST s a = ST (STBase.State s -> (a,STBase.State s))
39 instance Monad (ST s) where
41 return a = ST $ \ s -> (a,s)
42 m >> k = m >>= \ _ -> k
53 %*********************************************************
55 \subsection{Variables}
57 %*********************************************************
60 newSTRef :: a -> ST s (ST.STRef s a)
61 readSTRef :: ST.STRef s a -> ST s a
62 writeSTRef :: ST.STRef s a -> a -> ST s ()
64 newSTRef = strictToLazyST . ST.newSTRef
65 readSTRef = strictToLazyST . ST.readSTRef
66 writeSTRef r a = strictToLazyST (ST.writeSTRef r a)
69 %*********************************************************
73 %*********************************************************
76 type STArray s ix elt = MutableArray s ix elt
78 newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
79 readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt
80 writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
81 boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix)
82 thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
83 freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
84 unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
86 newSTArray ixs init = strictToLazyST (newArray ixs init)
87 readSTArray arr ix = strictToLazyST (readArray arr ix)
88 writeSTArray arr ix v = strictToLazyST (writeArray arr ix v)
89 boundsSTArray = boundsOfArray
90 thawSTArray = strictToLazyST . thawArray
91 freezeSTArray = strictToLazyST . freezeArray
92 unsafeFreezeSTArray = strictToLazyST . unsafeFreezeArray
94 strictToLazyST :: STBase.ST s a -> ST s a
95 strictToLazyST (STBase.ST m) = ST $ \s ->
96 let STBase.S# s# = s in
97 case m s# of { STBase.STret s2# r -> (r, STBase.S# s2#) }
99 lazyToStrictST :: ST s a -> STBase.ST s a
100 lazyToStrictST (ST m) = STBase.ST $ \s ->
101 case (m (STBase.S# s)) of (a, STBase.S# s') -> STBase.STret s' a