2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
4 \section[STBase]{The @ST@ and @PrimIO@ monads}
7 {-# OPTIONS -fno-implicit-prelude #-}
16 %*********************************************************
18 \subsection{The @ST@ monad}
20 %*********************************************************
22 The state-transformer monad proper. By default the monad is strict;
23 too many people got bitten by space leaks when it was lazy.
26 data State a = S# (State# a)
27 newtype ST s a = ST (State s -> (a, State s))
30 = case m (S# realWorld#) of
33 instance Monad (ST s) where
37 return x = ST $ \ s@(S# _) -> (x, s)
38 m >> k = m >>= \ _ -> k
42 case (m s) of {(r, new_s) ->
43 case (k r) of { ST k2 ->
46 {-# INLINE returnST #-}
48 -- here for backward compatibility:
49 returnST :: a -> ST s a
50 thenST :: ST s a -> (a -> ST s b) -> ST s b
51 seqST :: ST s a -> ST s b -> ST s b
57 unsafeInterleaveST :: ST s a -> ST s a -- ToDo: put in state-interface.tex
58 unsafeInterleaveST (ST m) = ST $ \ s ->
64 fixST :: (a -> ST s a) -> ST s a
72 -- more backward compatibility stuff:
73 listST :: [ST s a] -> ST s [a]
74 mapST :: (a -> ST s b) -> [a] -> ST s [b]
75 mapAndUnzipST :: (a -> ST s (b,c)) -> [a] -> ST s ([b],[c])
79 mapAndUnzipST = mapAndUnzipM
84 %*********************************************************
86 \subsection{The @PrimIO@ monad}
88 %*********************************************************
91 type PrimIO a = ST RealWorld a
93 fixPrimIO :: (a -> PrimIO a) -> PrimIO a
96 {-# GENERATE_SPECS unsafePerformPrimIO a #-}
97 unsafePerformPrimIO :: PrimIO a -> a
98 unsafeInterleavePrimIO :: PrimIO a -> PrimIO a
100 unsafePerformPrimIO = runST
101 unsafeInterleavePrimIO = unsafeInterleaveST
103 -- the following functions are now there for backward compatibility mostly:
105 {-# GENERATE_SPECS returnPrimIO a #-}
106 returnPrimIO :: a -> PrimIO a
108 {-# GENERATE_SPECS thenPrimIO b #-}
109 thenPrimIO :: PrimIO a -> (a -> PrimIO b) -> PrimIO b
111 {-# GENERATE_SPECS seqPrimIO b #-}
112 seqPrimIO :: PrimIO a -> PrimIO b -> PrimIO b
114 listPrimIO :: [PrimIO a] -> PrimIO [a]
115 mapPrimIO :: (a -> PrimIO b) -> [a] -> PrimIO [b]
116 mapAndUnzipPrimIO :: (a -> PrimIO (b,c)) -> [a] -> PrimIO ([b],[c])
118 {-# INLINE returnPrimIO #-}
119 {-# INLINE thenPrimIO #-}
120 {-# INLINE seqPrimIO #-}
122 returnPrimIO = return
125 listPrimIO = accumulate
127 mapAndUnzipPrimIO = mapAndUnzipM
131 %*********************************************************
133 \subsection{Ghastly return types}
135 %*********************************************************
138 data StateAndPtr# s elt = StateAndPtr# (State# s) elt
140 data StateAndChar# s = StateAndChar# (State# s) Char#
141 data StateAndInt# s = StateAndInt# (State# s) Int#
142 data StateAndWord# s = StateAndWord# (State# s) Word#
143 data StateAndFloat# s = StateAndFloat# (State# s) Float#
144 data StateAndDouble# s = StateAndDouble# (State# s) Double#
145 data StateAndAddr# s = StateAndAddr# (State# s) Addr#