7f35075e023f0b5153376e6abf7cdbffacf04f8d
[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 runST (ST m)
31   = case m realWorld# of
32       STret _ r -> r
33
34 instance Monad (ST s) where
35     {-# INLINE return #-}
36     {-# INLINE (>>)   #-}
37     {-# INLINE (>>=)  #-}
38     return x = ST $ \ s -> STret s x
39     m >> k   =  m >>= \ _ -> k
40
41     (ST m) >>= k
42       = ST $ \ s ->
43         case (m s) of { STret new_s r ->
44         case (k r) of { ST k2 ->
45         (k2 new_s) }}
46
47
48
49 fixST :: (a -> ST s a) -> ST s a
50 fixST k = ST $ \ s ->
51     let (ST k_r)  = k r
52         ans       = k_r s
53         STret _ r = ans
54     in
55     ans
56
57 \end{code}
58
59
60 %*********************************************************
61 %*                                                      *
62 \subsection{Ghastly return types}
63 %*                                                      *
64 %*********************************************************
65
66 The @State@ type is the return type of a _ccall_ with no result.  It
67 never actually exists, since it's always deconstructed straight away;
68 the desugarer ensures this.
69
70 \begin{code}
71 data State           s     = S#              (State# s)
72 data StateAndPtr#    s elt = StateAndPtr#    (State# s) elt 
73
74 data StateAndChar#   s     = StateAndChar#   (State# s) Char# 
75 data StateAndInt#    s     = StateAndInt#    (State# s) Int# 
76 data StateAndWord#   s     = StateAndWord#   (State# s) Word#
77 data StateAndFloat#  s     = StateAndFloat#  (State# s) Float# 
78 data StateAndDouble# s     = StateAndDouble# (State# s) Double#  
79 data StateAndAddr#   s     = StateAndAddr#   (State# s) Addr#
80 \end{code}