on master help sign in
Optimize filtering

Remove one layer of indirection

commit2ac9ec5854603306af1b00cc0d562121338d893d authorHarendra Kumar <harendra.kumar@gmail.com> dateThu 8 Mar 2018, 23:58 (9 years ago) parent61e479b
1 file changed+9−2
src/Streamly/Prelude.hs+9−2
src/Streamly/Prelude.hs+9−2
@@ -226,8 +226,15 @@ take n m = fromStream $ go n (toStream m)
226226
227227-- | Include only those elements that pass a predicate.
228228{-# INLINE filter #-}
229−filter :: (Streaming t, Monad (t m)) => (a -> Bool) -> t m a -> t m a
230−filter p m = m >>= \x -> if p x then return x else nil
229+filter :: Streaming t => (a -> Bool) -> t m a -> t m a
230+filter p m = fromStream $ go (toStream m)
231+ where
232+ go m1 = Stream $ \ctx stp yld -> do
233+ let yield a Nothing | p a = yld a Nothing
234+ | otherwise = stp
235+ yield a (Just x) | p a = yld a (Just (go x))
236+ | otherwise = (runStream x) ctx stp yield
237+ in (runStream m1) ctx stp yield
231238
232239-- | End the stream as soon as the predicate fails on an element.
233240takeWhile :: Streaming t => (a -> Bool) -> t m a -> t m a