7341cefd9fe160433f0e31b48ba35e0e3b8193eb
[ghc-base.git] / Control / Monad / ST.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Control.Monad.ST
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable (requires universal quantification for runST)
10 --
11 -- This library provides support for /strict/ state threads, as
12 -- described in the PLDI \'94 paper by John Launchbury and Simon Peyton
13 -- Jones /Lazy State Threads/.
14 --
15 -----------------------------------------------------------------------------
16
17 module Control.Monad.ST
18   (
19         -- * The 'ST' Monad
20         ST,             -- abstract, instance of Functor, Monad, Typeable.
21         runST,          -- :: (forall s. ST s a) -> a
22         fixST,          -- :: (a -> ST s a) -> ST s a
23
24         -- * Unsafe operations
25         unsafeInterleaveST,     -- :: ST s a -> ST s a
26         unsafeIOToST,           -- :: IO a -> ST s a
27
28         -- * Converting 'ST' to 'IO'
29         RealWorld,              -- abstract
30         stToIO                  -- :: ST RealWorld a -> IO a
31       ) where
32
33 import Prelude
34
35 import Control.Monad.Fix
36 import Data.Dynamic
37
38 #ifdef __HUGS__
39 import Hugs.ST
40 #endif
41
42 #ifdef __GLASGOW_HASKELL__
43 import GHC.ST
44 import GHC.Base         ( unsafeCoerce#, RealWorld )
45 import GHC.IOBase       ( IO(..), stToIO )
46
47 -- This relies on IO and ST having the same representation modulo the
48 -- constraint on the type of the state
49 --
50 unsafeIOToST        :: IO a -> ST s a
51 unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
52 #endif
53
54 instance MonadFix (ST s) where
55         mfix = fixST
56
57 -- ---------------------------------------------------------------------------
58 -- Typeable instance
59
60 sTTc :: TyCon
61 sTTc = mkTyCon "ST"
62
63 instance (Typeable a, Typeable b) => Typeable (ST a b) where
64   typeOf st = mkAppTy sTTc [typeOf ((undefined :: ST a b -> a) st),
65                             typeOf ((undefined :: ST a b -> b) st)]