on master help sign in
Add the monadic iterate function
c7b9463Abhiroop Sarkar
Changelog.md+1−1
@@ -7,7 +7,7 @@
7
7
8### Enhancements
8### Enhancements
9* Make `cons` right associative and provide an operator form `.:` for it
9* Make `cons` right associative and provide an operator form `.:` for it
10−* Add `iterate`, `null`, `tail`, `reverse`, `replicateM`, `scan` stream operations
10+* Add `iterateM`, `iterate`, `null`, `tail`, `reverse`, `replicateM`, `scan` stream operations
11* Improve performance of some stream operations (`foldl`, `dropWhile`)
11* Improve performance of some stream operations (`foldl`, `dropWhile`)
12
12
13### Bug Fixes
13### Bug Fixes
src/Streamly/Prelude.hs+9−1
@@ -25,6 +25,7 @@ module Streamly.Prelude
25 , unfoldrM
25 , unfoldrM
26 , each
26 , each
27 , iterate
27 , iterate
28+ , iterateM
28
29
29 -- * Elimination
30 -- * Elimination
30 -- ** General Folds
31 -- ** General Folds
@@ -126,8 +127,15 @@ each = Prelude.foldr cons nil
126iterate :: Streaming t => (a -> a) -> a -> t m a
127iterate :: Streaming t => (a -> a) -> a -> t m a
127iterate step = fromStream . go
128iterate step = fromStream . go
128 where
129 where
129− go s = scons s (Just (go (step s)))
130+ go s = scons s (Just (go (step s)))
130
131
132+-- | Iterate a monadic function from a seed value, streaming the results forever
133+iterateM :: (Streaming t, Monad m) => (a -> m a) -> m a -> t m a
134+iterateM step = fromStream . go
135+ where
136+ go ms = Stream $ \_ _ yld -> do
137+ s <- ms
138+ yld s (Just (go (step s)))
131
139
132-- | Read lines from an IO Handle into a stream of Strings.
140-- | Read lines from an IO Handle into a stream of Strings.
133fromHandle :: (Streaming t, MonadIO m) => IO.Handle -> t m String
141fromHandle :: (Streaming t, MonadIO m) => IO.Handle -> t m String