@@ -31,8 +31,11 @@ module Asyncly.Prelude
32 -- * Special folds
32 -- * Special folds
37 -- * Zipping
40 -- * Zipping
@@ -44,8 +47,8 @@ where
45import Control.Monad (liftM)
48import Control.Monad (liftM)
46import Data.Semigroup (Semigroup(..))
49import Data.Semigroup (Semigroup(..))
47−import Prelude hiding (drop, take, zipWith, foldr,
50+import Prelude hiding (filter, drop, dropWhile, take,
48− foldl)
51+ takeWhile, zipWith, foldr, foldl)
49import Asyncly.Core
52import Asyncly.Core
50import Asyncly.Streams
53import Asyncly.Streams
@@ -142,6 +145,28 @@ take n m = fromStream $ go n (toStream m)
143 else (runStream m1) ctx stp yield
146 else (runStream m1) ctx stp yield
148+-- | Include only those elements that pass a predicate.
149+filter :: Streaming t => (a -> Bool) -> t m a -> t m a
150+filter p m = fromStream $ go (toStream m)
152+ go m1 = Stream $ \ctx stp yld -> do
153+ let yield a Nothing | p a = yld a Nothing
155+ yield a (Just x) | p a = yld a (Just (go x))
156+ | otherwise = (runStream (go x)) ctx stp yield
157+ in (runStream m1) ctx stp yield
159+-- | End the stream as soon as the predicate fails on an element.
160+takeWhile :: Streaming t => (a -> Bool) -> t m a -> t m a
161+takeWhile p m = fromStream $ go (toStream m)
163+ go m1 = Stream $ \ctx stp yld -> do
164+ let yield a Nothing | p a = yld a Nothing
166+ yield a (Just x) | p a = yld a (Just (go x))
168+ in (runStream m1) ctx stp yield
145-- | Discard first 'n' elements from the stream and take the rest.
170-- | Discard first 'n' elements from the stream and take the rest.
146drop :: Streaming t => Int -> t m a -> t m a
171drop :: Streaming t => Int -> t m a -> t m a
147drop n m = fromStream $ go n (toStream m)
172drop n m = fromStream $ go n (toStream m)
@@ -153,6 +178,18 @@ drop n m = fromStream $ go n (toStream m)
153 then (runStream m1) ctx stp yld
178 then (runStream m1) ctx stp yld
154 else (runStream m1) ctx stp yield
179 else (runStream m1) ctx stp yield
181+-- | Drop elements in the stream as long as the predicate succeeds and then
182+-- take the rest of the stream.
183+dropWhile :: Streaming t => (a -> Bool) -> t m a -> t m a
184+dropWhile p m = fromStream $ go (toStream m)
186+ go m1 = Stream $ \ctx stp yld -> do
187+ let yield a Nothing | p a = stp
188+ | otherwise = yld a Nothing
189+ yield a (Just x) | p a = (runStream (go x)) ctx stp yield
190+ | otherwise = yld a (Just x)
191+ in (runStream m1) ctx stp yield
156------------------------------------------------------------------------------
193------------------------------------------------------------------------------
157-- Serially Zipping Streams
194-- Serially Zipping Streams
158------------------------------------------------------------------------------
195------------------------------------------------------------------------------