on master help sign in
Return an array slice in "strip"
8d9a164Harendra Kumar
core/src/Streamly/Internal/Data/Array/Generic.hs+13−11
@@ -223,34 +223,36 @@ sliceUnsafe offset len (Array cont off1 _) = Array cont (off1 + offset) len
223-- XXX This is not efficient as it copies the array. We should support array
223-- XXX This is not efficient as it copies the array. We should support array
224-- slicing so that we can just refer to the underlying array memory instead of
224-- slicing so that we can just refer to the underlying array memory instead of
225-- copying.
225-- copying.
226−--
226+
227-- | Truncate the array at the beginning and end as long as the predicate
227-- | Truncate the array at the beginning and end as long as the predicate
228−-- holds true.
228+-- holds true. Returns a slice of the original array.
229strip :: (a -> Bool) -> Array a -> Array a
229strip :: (a -> Bool) -> Array a -> Array a
230strip p arr =
230strip p arr =
231 let lastIndex = length arr - 1
231 let lastIndex = length arr - 1
232 indexR = getIndexR lastIndex -- last predicate failing index
232 indexR = getIndexR lastIndex -- last predicate failing index
233− in if indexR == -1
233+ in if indexR < 0
234 then nil
234 then nil
235 else
235 else
236 let indexL = getIndexL 0 -- first predicate failing index
236 let indexL = getIndexL 0 -- first predicate failing index
237 in if indexL == 0 && indexR == lastIndex
237 in if indexL == 0 && indexR == lastIndex
238 then arr
238 then arr
239− else unsafeFreeze $ unsafePerformIO $ do
239+ else
240 let newLen = indexR - indexL + 1
240 let newLen = indexR - indexL + 1
241− arrThawed = unsafeThaw (sliceUnsafe indexL newLen arr)
241+ in sliceUnsafe indexL newLen arr
242− MArray.clone arrThawed
243
242
244 where
243 where
245
244
246 getIndexR idx
245 getIndexR idx
247 | idx < 0 = idx
246 | idx < 0 = idx
248 | otherwise =
247 | otherwise =
249− if p (getIndexUnsafe idx arr) then getIndexR (idx - 1) else idx
248+ if p (getIndexUnsafe idx arr)
250−
249+ then getIndexR (idx - 1)
250+ else idx
251+
252+ getIndexL idx =
251− getIndexL idx = if p (getIndexUnsafe idx arr)
253+ if p (getIndexUnsafe idx arr)
252− then getIndexL (idx + 1)
254+ then getIndexL (idx + 1)
253− else idx
255+ else idx
254
256
255-------------------------------------------------------------------------------
257-------------------------------------------------------------------------------
256-- Instances
258-- Instances