on master help sign in
Rewrite filter for performance

Previous implementation was order of magnitude worse

commitc997b72f1df9945d47a69ded80b8a75c47c85066 authorHarendra Kumar <harendra.kumar@gmail.com> dateTue 31 Oct 2017, 15:24 (9 years ago) parent10fa995
1 file changed+7−9
src/Asyncly/Prelude.hs+7−9
src/Asyncly/Prelude.hs+7−9
@@ -207,16 +207,14 @@ take n m = fromStream $ go n (toStream m)
207207 then stp
208208 else (runStream m1) ctx stp yield
209209
210+-- XXX This is not as efficient as it could be. We need a short circuiting at
211+-- a lower level. Compare with simple-conduit, filtering there cuts down time
212+-- due to short circuting whereas the time spent remains the same here.
213+
210214-- | Include only those elements that pass a predicate.
211−filter :: Streaming t => (a -> Bool) -> t m a -> t m a
212−filter p m = fromStream $ go (toStream m)
213− where
214− go m1 = Stream $ \ctx stp yld -> do
215− let yield a Nothing | p a = yld a Nothing
216− | otherwise = stp
217− yield a (Just x) | p a = yld a (Just (go x))
218− | otherwise = (runStream (go x)) ctx stp yield
219− in (runStream m1) ctx stp yield
215+{-# INLINE filter #-}
216+filter :: (Streaming t, Monad (t m)) => (a -> Bool) -> t m a -> t m a
217+filter p m = m >>= \x -> if p x then return x else nil
220218
221219-- | End the stream as soon as the predicate fails on an element.
222220takeWhile :: Streaming t => (a -> Bool) -> t m a -> t m a