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