Add replicateM operation

This commit is contained in:
Harendra Kumar 2018-03-16 02:41:44 +05:30
parent 84542d2768
commit 29bc664825
3 changed files with 19 additions and 1 deletions

View File

@ -1,7 +1,7 @@
## Unreleased
### Enhancements
* Add the `scan` operation for left scan of a stream
* Add `replicateM`, `scan` stream operations
* Improve performance of some stream operations (`foldl`, `dropWhile`)
### Bug Fixes

View File

@ -59,6 +59,7 @@ module Streamly.Prelude
, mapM
, mapM_
, sequence
, replicateM
-- * Zipping
, zipWith
@ -431,6 +432,14 @@ sequence m = fromStream $ go (toStream m)
yield a (Just x) = a >>= \b -> yld b (Just (go x))
in (runStream m1) Nothing stop yield
replicateM :: (Streaming t, Monad m) => Int -> m a -> t m a
replicateM n m = fromStream $ go n
where
go cnt = Stream $ \_ stp yld ->
if cnt <= 0
then stp
else m >>= \a -> yld a (Just $ go (cnt - 1))
------------------------------------------------------------------------------
-- Serially Zipping Streams
------------------------------------------------------------------------------

View File

@ -4,6 +4,7 @@
module Main (main) where
import Control.Concurrent (threadDelay)
import Control.Monad (replicateM)
import Data.Foldable (forM_)
import Data.List (sort)
import Test.Hspec
@ -637,6 +638,14 @@ mixedOps = do
streamOperations :: Streaming t => (t IO Int, [Int], Int) -> Spec
streamOperations (stream, list, len) = do
-- Generation
it "replicateM" $ do
let x = return (1 :: Int)
str <- A.toList . serially $ A.replicateM len x
lst <- replicateM len x
return $ str == lst
`shouldReturn` True
-- Filtering
it "filter all out" $ transform (A.filter (> len)) (filter (> len))
it "filter all in" $ transform (A.filter (<= len)) (filter (<= len))