1 -----------------------------------------------------------------------------
3 -- Module : Control.Monad.ST.Lazy
4 -- Copyright : (c) The University of Glasgow 2001
5 -- License : BSD-style (see the file libraries/base/LICENSE)
7 -- Maintainer : libraries@haskell.org
8 -- Stability : provisional
9 -- Portability : non-portable (requires universal quantification for runST)
11 -- This module presents an identical interface to "Control.Monad.ST",
12 -- but the underlying implementation of the state thread is /lazy/ (in
13 -- the sense that (@_|_ >> a@ is not necessarily equal to @_|_@).
15 -----------------------------------------------------------------------------
17 module Control.Monad.ST.Lazy (
23 -- * Unsafe operations
27 -- * Converting 'ST' To 'IO'
31 -- * Converting between strict and lazy 'ST'
32 strictToLazyST, lazyToStrictST
37 #ifdef __GLASGOW_HASKELL__
38 import qualified Control.Monad.ST as ST
39 import qualified GHC.ST
44 #ifdef __GLASGOW_HASKELL__
45 newtype ST s a = ST (State s -> (a, State s))
46 data State s = S# (State# s)
49 instance Functor (ST s) where
50 fmap f m = ST $ \ s ->
57 instance Monad (ST s) where
59 return a = ST $ \ s -> (a,s)
60 m >> k = m >>= \ _ -> k
72 #ifdef __GLASGOW_HASKELL__
73 {-# NOINLINE runST #-}
74 runST :: (forall s. ST s a) -> a
75 runST st = case st of ST the_st -> let (r,_) = the_st (S# realWorld#) in r
77 fixST :: (a -> ST s a) -> ST s a
86 -- ---------------------------------------------------------------------------
89 #ifdef __GLASGOW_HASKELL__
91 Convert a strict 'ST' computation into a lazy one. The strict state
92 thread passed to 'strictToLazyST' is not performed until the result of
93 the lazy state thread it returns is demanded.
95 strictToLazyST :: ST.ST s a -> ST s a
96 strictToLazyST m = ST $ \s ->
98 pr = case s of { S# s# -> GHC.ST.liftST m s# }
99 r = case pr of { GHC.ST.STret _ v -> v }
100 s' = case pr of { GHC.ST.STret s2# _ -> S# s2# }
105 Convert a lazy 'ST' computation into a strict one.
107 lazyToStrictST :: ST s a -> ST.ST s a
108 lazyToStrictST (ST m) = GHC.ST.ST $ \s ->
109 case (m (S# s)) of (a, S# s') -> (# s', a #)
112 unsafeInterleaveST :: ST s a -> ST s a
113 unsafeInterleaveST = strictToLazyST . ST.unsafeInterleaveST . lazyToStrictST