on master help sign in
Optimize filtering
2ac9ec5Harendra Kumar
src/Streamly/Prelude.hs+9−2
@@ -226,8 +226,15 @@ take n m = fromStream $ go n (toStream m)
226
226
227-- | Include only those elements that pass a predicate.
227-- | Include only those elements that pass a predicate.
228{-# INLINE filter #-}
228{-# INLINE filter #-}
229−filter :: (Streaming t, Monad (t m)) => (a -> Bool) -> t m a -> t m a
229+filter :: Streaming t => (a -> Bool) -> t m a -> t m a
230−filter p m = m >>= \x -> if p x then return x else nil
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
231
238
232-- | End the stream as soon as the predicate fails on an element.
239-- | End the stream as soon as the predicate fails on an element.
233takeWhile :: Streaming t => (a -> Bool) -> t m a -> t m a
240takeWhile :: Streaming t => (a -> Bool) -> t m a -> t m a