68dd330dba329b6aaa353d4d3cd0c5587b3d3ff9
[ghc-hetmet.git] / ghc / lib / ghc / STBase.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[STBase]{The @ST@ monad}
5
6 \begin{code}
7 {-# OPTIONS -fno-implicit-prelude #-}
8
9 module STBase where
10
11 import Monad
12 import PrelBase
13 import GHC
14 \end{code}
15
16 %*********************************************************
17 %*                                                      *
18 \subsection{The @ST@ monad}
19 %*                                                      *
20 %*********************************************************
21
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.
24
25 \begin{code}
26 newtype ST s a = ST (State# s -> STret s a)
27
28 data STret s a = STret (State# s) a
29
30 instance Monad (ST s) where
31     {-# INLINE return #-}
32     {-# INLINE (>>)   #-}
33     {-# INLINE (>>=)  #-}
34     return x = ST $ \ s -> STret s x
35     m >> k   =  m >>= \ _ -> k
36
37     (ST m) >>= k
38       = ST $ \ s ->
39         case (m s) of { STret new_s r ->
40         case (k r) of { ST k2 ->
41         (k2 new_s) }}
42
43
44
45 fixST :: (a -> ST s a) -> ST s a
46 fixST k = ST $ \ s ->
47     let (ST k_r)  = k r
48         ans       = k_r s
49         STret _ r = ans
50     in
51     ans
52
53 \end{code}
54
55
56 %*********************************************************
57 %*                                                      *
58 \subsection{Ghastly return types}
59 %*                                                      *
60 %*********************************************************
61
62 The @State@ type is the return type of a _ccall_ with no result.  It
63 never actually exists, since it's always deconstructed straight away;
64 the desugarer ensures this.
65
66 \begin{code}
67 data State           s     = S#              (State# s)
68 data StateAndPtr#    s elt = StateAndPtr#    (State# s) elt 
69
70 data StateAndChar#   s     = StateAndChar#   (State# s) Char# 
71 data StateAndInt#    s     = StateAndInt#    (State# s) Int# 
72 data StateAndWord#   s     = StateAndWord#   (State# s) Word#
73 data StateAndFloat#  s     = StateAndFloat#  (State# s) Float# 
74 data StateAndDouble# s     = StateAndDouble# (State# s) Double#  
75 data StateAndAddr#   s     = StateAndAddr#   (State# s) Addr#
76 \end{code}