828ae63ffa6d4b3e2a955e1098746a38ab0adbb1
[packages/random.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 (uses Data.Array.MArray)
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.Array ( Array )
38 import Hugs.ST ( STArray, unsafeFreezeSTArray )
39 #endif
40
41 #ifdef __GLASGOW_HASKELL__
42 import GHC.Arr ( STArray, Array, unsafeFreezeSTArray )
43 #endif
44
45 -- | A safe way to create and work with a mutable array before returning an
46 -- immutable array for later perusal. This function avoids copying
47 -- the array before returning it - it uses 'unsafeFreeze' internally, but
48 -- this wrapper is a safe interface to that function.
49 --
50 runSTArray :: (Ix i)
51 => (forall s . ST s (STArray s i e))
52 -> Array i e
53 runSTArray st = runST (st >>= unsafeFreezeSTArray)
54
55 -- | A safe way to create and work with an unboxed mutable array before
56 -- returning an immutable array for later perusal. This function
57 -- avoids copying the array before returning it - it uses
58 -- 'unsafeFreeze' internally, but this wrapper is a safe interface to
59 -- that function.
60 --
61 runSTUArray :: (Ix i)
62 => (forall s . ST s (STUArray s i e))
63 -> UArray i e
64 runSTUArray st = runST (st >>= unsafeFreezeSTUArray)
65
66
67 -- INTERESTING... this is the type we'd like to give to runSTUArray:
68 --
69 -- runSTUArray :: (Ix i, IArray UArray e,
70 -- forall s. MArray (STUArray s) e (ST s))
71 -- => (forall s . ST s (STUArray s i e))
72 -- -> UArray i e
73 --
74 -- Note the quantified constraint. We dodged the problem by using
75 -- unsafeFreezeSTUArray directly in the defn of runSTUArray above, but
76 -- this essentially constrains us to a single unsafeFreeze for all STUArrays
77 -- (in theory we might have a different one for certain element types).