@@ -60,6 +60,7 @@ module Data.Sequence (
60
60
fromList , -- :: [a] -> Seq a
61
61
fromFunction , -- :: Int -> (Int -> a) -> Seq a
62
62
fromArray , -- :: Ix i => Array i a -> Seq a
63
+ fromArrayMonolithic , -- :: Ix i => Array i a -> Seq a
63
64
-- ** Repetition
64
65
replicate , -- :: Int -> a -> Seq a
65
66
replicateA , -- :: Applicative f => Int -> f a -> f (Seq a)
@@ -177,6 +178,9 @@ import Data.Data
177
178
import Data.Array (Ix , Array )
178
179
#ifdef __GLASGOW_HASKELL__
179
180
import qualified GHC.Arr
181
+ import qualified Data.Primitive.Array as PA
182
+ import Data.STRef
183
+ import Control.Monad.ST
180
184
#endif
181
185
182
186
-- Coercion on GHC 7.8+
@@ -1643,6 +1647,7 @@ fromArray a = fromFunction (GHC.Arr.numElements a) (GHC.Arr.unsafeAt a)
1643
1647
fromArray a = fromList2 (Data.Array. rangeSize (Data.Array. bounds a)) (Data.Array. elems a)
1644
1648
#endif
1645
1649
1650
+
1646
1651
-- Splitting
1647
1652
1648
1653
-- | /O(log(min(i,n-i)))/. The first @i@ elements of a sequence.
@@ -2335,14 +2340,39 @@ unstableSortBy cmp (Seq xs) =
2335
2340
toPQ cmp (\ (Elem x) -> PQueue x Nil ) xs
2336
2341
2337
2342
-- | fromList2, given a list and its length, constructs a completely
2338
- -- balanced Seq whose elements are that list using the applicativeTree
2343
+ -- balanced Seq whose elements are that list using the replicateA
2339
2344
-- generalization.
2340
2345
fromList2 :: Int -> [a ] -> Seq a
2341
2346
fromList2 n = execState (replicateA n (State ht))
2342
2347
where
2343
2348
ht (x: xs) = (xs, x)
2344
2349
ht [] = error " fromList2: short list"
2345
2350
2351
+ -- | /O(n)/. Create a sequence consisting of the elements of an 'Array'. With
2352
+ -- GHC, the result of 'fromArrayMonolithic' is guaranteed not to retain any
2353
+ -- references to the array, unless individual array entries contain such. To
2354
+ -- accomplish this, it reads each entry out of the array before returning. With
2355
+ -- other implementations, or with GHC before base 4.4.0, this is identical to
2356
+ -- 'fromArray'.
2357
+ fromArrayMonolithic :: Ix i => Array i a -> Seq a
2358
+ #if defined(__GLASGOW_HASKELL__) && MIN_VERSION_base(4,4,0)
2359
+ fromArrayMonolithic (GHC.Arr. Array _ _ len ar)
2360
+ = runST (fromArrayMonolithicST (PA. Array ar))
2361
+ where
2362
+ {-# INLINE fromArrayMonolithicST #-}
2363
+ fromArrayMonolithicST :: PA. Array a -> ST s (Seq a )
2364
+ fromArrayMonolithicST a =
2365
+ do
2366
+ i <- newSTRef (0 :: Int )
2367
+ replicateA len (do
2368
+ i' <- readSTRef i
2369
+ x <- PA. indexArrayM a i'
2370
+ writeSTRef i (i'+ 1 )
2371
+ return x)
2372
+ #else
2373
+ fromArrayMonolithic = fromArray
2374
+ #endif
2375
+
2346
2376
-- | A 'PQueue' is a simple pairing heap.
2347
2377
data PQueue e = PQueue e (PQL e )
2348
2378
data PQL e = Nil | {- # UNPACK #-} !(PQueue e ) :& PQL e
0 commit comments