on master help sign in
Add strip API to Array
commitb06596fcc900b0a360ecc37d72a7131a3e2153f2 authorRanjeet Kumar Ranjan <ranjeetr@composewell.com> dateSun 26 Sep 2021, 15:50 (5 years ago) parent409a3d8
1 file changed+35
src/Streamly/Internal/Data/Array.hs+35
src/Streamly/Internal/Data/Array.hs+35
@@ -16,6 +16,7 @@ module Streamly.Internal.Data.Array
1616 ( Array(..)
1717
1818 -- * Construction
19+ , nil
1920 , writeN
2021 , write
2122 , writeLastN
@@ -44,6 +45,7 @@ module Streamly.Internal.Data.Array
4445
4546 -- * Random Access
4647 , getIndexUnsafe
48+ , strip
4749 )
4850where
4951
@@ -74,6 +76,12 @@ import Prelude hiding (foldr, length, read)
7476bottomElement :: a
7577bottomElement = undefined
7678
79+{-# NOINLINE nil #-}
80+nil :: Array a
81+nil = unsafePerformIO $ do
82+ marr <- liftIO $ newArray 0 bottomElement
83+ liftIO $ freezeArray marr 0 0
84+
7785-------------------------------------------------------------------------------
7886-- Construction - Folds
7987-------------------------------------------------------------------------------
@@ -278,3 +286,30 @@ writeLastN n
278286 liftIO $ copyMutableArray arr' 0 (RB.arr rb) ref (n - ref)
279287 liftIO $ copyMutableArray arr' (n - ref) (RB.arr rb) 0 ref
280288 liftIO $ unsafeFreezeArray arr'
289+
290+-- XXX This is not efficient as it copies the array. We should support array
291+-- slicing so that we can just refer to the underlying array memory instead of
292+-- copying.
293+--
294+-- | Truncate the array at the beginning and end as long as the predicate
295+-- holds true.
296+strip :: (a -> Bool) -> Array a -> Array a
297+strip p arr =
298+ let lastIndex = length arr - 1
299+ indexR = getIndexR lastIndex -- last predicate failing index
300+ in if indexR == -1
301+ then nil
302+ else
303+ let indexL = getIndexL 0 -- first predicate failing index
304+ in if indexL == 0 && indexR == lastIndex
305+ then arr
306+ else cloneArray arr indexL (indexR - indexL + 1)
307+
308+ where
309+
310+ getIndexR idx
311+ | idx < 0 = idx
312+ | otherwise =
313+ if p (indexArray arr idx) then getIndexR (idx - 1) else idx
314+
315+ getIndexL idx = if p (indexArray arr idx) then getIndexL (idx + 1) else idx