@@ -60,6 +60,7 @@ module Data.Sequence (
6060 fromList , -- :: [a] -> Seq a
6161 fromFunction , -- :: Int -> (Int -> a) -> Seq a
6262 fromArray , -- :: Ix i => Array i a -> Seq a
63+ fromArrayMonolithic , -- :: Ix i => Array i a -> Seq a
6364 -- ** Repetition
6465 replicate , -- :: Int -> a -> Seq a
6566 replicateA , -- :: Applicative f => Int -> f a -> f (Seq a)
@@ -177,6 +178,9 @@ import Data.Data
177178import Data.Array (Ix , Array )
178179#ifdef __GLASGOW_HASKELL__
179180import qualified GHC.Arr
181+ import qualified Data.Primitive.Array as PA
182+ import Data.STRef
183+ import Control.Monad.ST
180184#endif
181185
182186-- Coercion on GHC 7.8+
@@ -1643,6 +1647,7 @@ fromArray a = fromFunction (GHC.Arr.numElements a) (GHC.Arr.unsafeAt a)
16431647fromArray a = fromList2 (Data.Array. rangeSize (Data.Array. bounds a)) (Data.Array. elems a)
16441648#endif
16451649
1650+
16461651-- Splitting
16471652
16481653-- | /O(log(min(i,n-i)))/. The first @i@ elements of a sequence.
@@ -2335,14 +2340,39 @@ unstableSortBy cmp (Seq xs) =
23352340 toPQ cmp (\ (Elem x) -> PQueue x Nil ) xs
23362341
23372342-- | 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
23392344-- generalization.
23402345fromList2 :: Int -> [a ] -> Seq a
23412346fromList2 n = execState (replicateA n (State ht))
23422347 where
23432348 ht (x: xs) = (xs, x)
23442349 ht [] = error " fromList2: short list"
23452350
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+
23462376-- | A 'PQueue' is a simple pairing heap.
23472377data PQueue e = PQueue e (PQL e )
23482378data PQL e = Nil | {- # UNPACK #-} !(PQueue e ) :& PQL e
0 commit comments