@@ -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