on master help sign in
Add pure unfoldr
commitb1e400ba2d01f83017889d87891fbc3c644c4a64 authorHarendra Kumar <harendra.kumar@gmail.com> dateMon 20 Nov 2017, 17:04 (9 years ago) parent9435cdc
1 file changed+17−6
src/Asyncly/Prelude.hs+17−6
src/Asyncly/Prelude.hs+17−6
@@ -23,6 +23,7 @@ module Asyncly.Prelude
2323 cons
2424 , nil
2525 , unfoldr
26+ , unfoldrM
2627 , each
2728 , fromHandle
2829
@@ -87,9 +88,18 @@ import Asyncly.Streams
8788-- Construction
8889------------------------------------------------------------------------------
8990
90−-- | Build a Stream by unfolding steps starting from a seed.
91−unfoldr :: (Streaming t, Monad m) => (b -> m (Maybe (a, b))) -> b -> t m a
91+-- | Build a Stream by unfolding pure steps starting from a seed.
92+unfoldr :: Streaming t => (b -> Maybe (a, b)) -> b -> t m a
9293unfoldr step = fromStream . go
94+ where
95+ go s = Stream $ \_ stp yld -> do
96+ case step s of
97+ Nothing -> stp
98+ Just (a, b) -> yld a (Just (go b))
99+
100+-- | Build a Stream by unfolding monadic steps starting from a seed.
101+unfoldrM :: (Streaming t, Monad m) => (b -> m (Maybe (a, b))) -> b -> t m a
102+unfoldrM step = fromStream . go
93103 where
94104 go s = Stream $ \_ stp yld -> do
95105 mayb <- step s
@@ -354,8 +364,8 @@ maximum m = go Nothing (toStream m)
354364
355365-- XXX Parallel variants of these? mapMWith et al. sequenceWith.
356366
357−-- | Apply a monadic action to each element of the stream and replace it with
358−-- the result.
367+-- | Replace each element of the stream with the result of a monadic action
368+-- applied on the element.
359369mapM :: (Streaming t, Monad m) => (a -> m b) -> t m a -> t m b
360370mapM f m = fromStream $ go (toStream m)
361371 where
@@ -366,7 +376,7 @@ mapM f m = fromStream $ go (toStream m)
366376 in (runStream m1) Nothing stop yield
367377
368378-- | Apply a monadic action to each element of the stream and discard the
369−-- results.
379+-- output of the action.
370380mapM_ :: (Streaming t, Monad m) => (a -> m b) -> t m a -> m ()
371381mapM_ f m = go (toStream m)
372382 where
@@ -376,7 +386,8 @@ mapM_ f m = go (toStream m)
376386 yield a (Just x) = f a >> go x
377387 in (runStream m1) Nothing stop yield
378388
379−-- | Reduce a stream of monadic actions to a stream of their results.
389+-- | Reduce a stream of monadic actions to a stream of the output of those
390+-- actions.
380391sequence :: (Streaming t, Monad m) => t m (m a) -> t m a
381392sequence m = fromStream $ go (toStream m)
382393 where