on master help sign in
Add filter, takeWhile, dropWhile
commit45aee371b5124d378ed9e098b988a8c31d2922af authorHarendra Kumar <harendra.kumar@gmail.com> dateSat 28 Oct 2017, 12:38 (9 years ago) parentf580793
1 file changed+39−2
src/Asyncly/Prelude.hs+39−2
src/Asyncly/Prelude.hs+39−2
@@ -31,8 +31,11 @@ module Asyncly.Prelude
3131
3232 -- * Special folds
3333 , toList
34+ , filter
3435 , take
36+ , takeWhile
3537 , drop
38+ , dropWhile
3639
3740 -- * Zipping
3841 , zipWith
@@ -44,8 +47,8 @@ where
4447
4548import Control.Monad (liftM)
4649import Data.Semigroup (Semigroup(..))
47−import Prelude hiding (drop, take, zipWith, foldr,
48− foldl)
50+import Prelude hiding (filter, drop, dropWhile, take,
51+ takeWhile, zipWith, foldr, foldl)
4952import Asyncly.Core
5053import Asyncly.Streams
5154
@@ -142,6 +145,28 @@ take n m = fromStream $ go n (toStream m)
142145 then stp
143146 else (runStream m1) ctx stp yield
144147
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)
151+ where
152+ go m1 = Stream $ \ctx stp yld -> do
153+ let yield a Nothing | p a = yld a Nothing
154+ | otherwise = stp
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
158+
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)
162+ where
163+ go m1 = Stream $ \ctx stp yld -> do
164+ let yield a Nothing | p a = yld a Nothing
165+ | otherwise = stp
166+ yield a (Just x) | p a = yld a (Just (go x))
167+ | otherwise = stp
168+ in (runStream m1) ctx stp yield
169+
145170-- | Discard first 'n' elements from the stream and take the rest.
146171drop :: Streaming t => Int -> t m a -> t m a
147172drop n m = fromStream $ go n (toStream m)
@@ -153,6 +178,18 @@ drop n m = fromStream $ go n (toStream m)
153178 then (runStream m1) ctx stp yld
154179 else (runStream m1) ctx stp yield
155180
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)
185+ where
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
192+
156193------------------------------------------------------------------------------
157194-- Serially Zipping Streams
158195------------------------------------------------------------------------------