e8de28f00328f5c5af9621754582996d819ac26a
[ghc-base.git] / Data / Array / ST.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Array.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
10 --
11 -- Mutable boxed and unboxed arrays in the 'Control.Monad.ST.ST' monad.
12 --
13 -----------------------------------------------------------------------------
14
15 module Data.Array.ST (
16
17    -- * Boxed arrays
18    STArray,             -- instance of: Eq, MArray
19    runSTArray,
20
21    -- * Unboxed arrays
22    STUArray,            -- instance of: Eq, MArray
23    runSTUArray,
24    castSTUArray,        -- :: STUArray s i a -> ST s (STUArray s i b)
25
26    -- * Overloaded mutable array interface
27    module Data.Array.MArray,
28  ) where
29
30 import Prelude
31
32 import Data.Array.MArray
33 import Data.Array.Base  ( STUArray, castSTUArray, UArray, unsafeFreezeSTUArray )
34 import Control.Monad.ST ( ST, runST )
35
36 #ifdef __HUGS__
37 import Hugs.ST          ( STArray )
38 #endif
39
40 #ifdef __GLASGOW_HASKELL__
41 import GHC.Arr          ( STArray, Array )
42 #endif
43
44 -- | A safe way to create and work with a mutable array before returning an
45 -- immutable array for later perusal.  This function avoids copying
46 -- the array before returning it - it uses 'unsafeFreeze' internally, but
47 -- this wrapper is a safe interface to that function.
48 --
49 runSTArray :: (Ix i)
50            => (forall s . ST s (STArray s i e))
51            -> Array i e
52 runSTArray st = runST (st >>= unsafeFreeze)
53
54 -- | A safe way to create and work with an unboxed mutable array before
55 -- returning an immutable array for later perusal.  This function
56 -- avoids copying the array before returning it - it uses
57 -- 'unsafeFreeze' internally, but this wrapper is a safe interface to
58 -- that function.
59 --
60 runSTUArray :: (Ix i)
61            => (forall s . ST s (STUArray s i e))
62            -> UArray i e
63 runSTUArray st = runST (st >>= unsafeFreezeSTUArray)
64
65
66 -- INTERESTING... this is the type we'd like to give to runSTUArray:
67 --
68 -- runSTUArray :: (Ix i, IArray UArray e, 
69 --              forall s. MArray (STUArray s) e (ST s))
70 --         => (forall s . ST s (STUArray s i e))
71 --         -> UArray i e
72 --
73 -- Note the quantified constraint.  We dodged the problem by using
74 -- unsafeFreezeSTUArray directly in the defn of runSTUArray above, but
75 -- this essentially constrains us to a single unsafeFreeze for all STUArrays
76 -- (in theory we might have a different one for certain element types).