on master help sign in
Add replicateM operation
29bc664Harendra Kumar
Changelog.md+1−1
@@ -1,7 +1,7 @@
1## Unreleased
1## Unreleased
2
2
3### Enhancements
3### Enhancements
4−* Add the `scan` operation for left scan of a stream
4+* Add `replicateM`, `scan` stream operations
5* Improve performance of some stream operations (`foldl`, `dropWhile`)
5* Improve performance of some stream operations (`foldl`, `dropWhile`)
6
6
7### Bug Fixes
7### Bug Fixes
src/Streamly/Prelude.hs+9
@@ -59,6 +59,7 @@ module Streamly.Prelude
59 , mapM
59 , mapM
60 , mapM_
60 , mapM_
61 , sequence
61 , sequence
62+ , replicateM
62
63
63 -- * Zipping
64 -- * Zipping
64 , zipWith
65 , zipWith
@@ -431,6 +432,14 @@ sequence m = fromStream $ go (toStream m)
431 yield a (Just x) = a >>= \b -> yld b (Just (go x))
432 yield a (Just x) = a >>= \b -> yld b (Just (go x))
432 in (runStream m1) Nothing stop yield
433 in (runStream m1) Nothing stop yield
433
434
435+replicateM :: (Streaming t, Monad m) => Int -> m a -> t m a
436+replicateM n m = fromStream $ go n
437+ where
438+ go cnt = Stream $ \_ stp yld ->
439+ if cnt <= 0
440+ then stp
441+ else m >>= \a -> yld a (Just $ go (cnt - 1))
442+
434------------------------------------------------------------------------------
443------------------------------------------------------------------------------
435-- Serially Zipping Streams
444-- Serially Zipping Streams
436------------------------------------------------------------------------------
445------------------------------------------------------------------------------
test/Main.hs+9
@@ -4,6 +4,7 @@
4module Main (main) where
4module Main (main) where
5
5
6import Control.Concurrent (threadDelay)
6import Control.Concurrent (threadDelay)
7+import Control.Monad (replicateM)
7import Data.Foldable (forM_)
8import Data.Foldable (forM_)
8import Data.List (sort)
9import Data.List (sort)
9import Test.Hspec
10import Test.Hspec
@@ -637,6 +638,14 @@ mixedOps = do
637streamOperations :: Streaming t => (t IO Int, [Int], Int) -> Spec
638streamOperations :: Streaming t => (t IO Int, [Int], Int) -> Spec
638streamOperations (stream, list, len) = do
639streamOperations (stream, list, len) = do
639
640
641+ -- Generation
642+ it "replicateM" $ do
643+ let x = return (1 :: Int)
644+ str <- A.toList . serially $ A.replicateM len x
645+ lst <- replicateM len x
646+ return $ str == lst
647+ `shouldReturn` True
648+
640 -- Filtering
649 -- Filtering
641 it "filter all out" $ transform (A.filter (> len)) (filter (> len))
650 it "filter all out" $ transform (A.filter (> len)) (filter (> len))
642 it "filter all in" $ transform (A.filter (<= len)) (filter (<= len))
651 it "filter all in" $ transform (A.filter (<= len)) (filter (<= len))