on master help sign in
implement stream to unfold conversions
commit5da3375b484ee85aa31297758870b5613c2ad7b7 authorHarendra Kumar <harendra.kumar@gmail.com> dateThu 10 Oct 2019, 22:00 (7 years ago) parent90f0a97
1 file changed+42
src/Streamly/Internal/Data/Unfold.hs+42
src/Streamly/Internal/Data/Unfold.hs+42
@@ -71,6 +71,9 @@ module Streamly.Internal.Data.Unfold
7171 -- pipe
7272
7373 -- * Unfolds
74+ , fromStream
75+ , fromStream1
76+ , fromStream2
7477 , singleton
7578 , replicateM
7679 , fromList
@@ -118,6 +121,8 @@ import Streamly.Internal.Data.SVar (defState)
118121import Control.Monad.Catch (MonadCatch)
119122
120123import qualified Control.Monad.Catch as MC
124+import qualified Streamly.Streams.StreamK as K
125+import qualified Streamly.Streams.StreamD as D
121126
122127-------------------------------------------------------------------------------
123128-- Input operations
@@ -195,6 +200,43 @@ map f (Unfold ustep uinject) = Unfold step uinject
195200 Skip s -> Skip s
196201 Stop -> Stop
197202
203+-------------------------------------------------------------------------------
204+-- Convert streams into unfolds
205+-------------------------------------------------------------------------------
206+
207+{-# INLINE_LATE streamStep #-}
208+streamStep :: Monad m => Stream m a -> m (Step (Stream m a) a)
209+streamStep (Stream step1 state) = do
210+ r <- step1 defState state
211+ return $ case r of
212+ Yield x s -> Yield x (Stream step1 s)
213+ Skip s -> Skip (Stream step1 s)
214+ Stop -> Stop
215+
216+-- | Convert a stream into an 'Unfold'. Note that a stream converted to an
217+-- 'Unfold' may not be as efficient as an 'Unfold' in some situations.
218+--
219+-- /Internal/
220+fromStream :: (K.IsStream t, Monad m) => t m b -> Unfold m Void b
221+fromStream str = Unfold streamStep (\_ -> return $ D.toStreamD str)
222+
223+-- | Convert a single argument stream generator function into an
224+-- 'Unfold'. Note that a stream converted to an 'Unfold' may not be as
225+-- efficient as an 'Unfold' in some situations.
226+--
227+-- /Internal/
228+fromStream1 :: (K.IsStream t, Monad m) => (a -> t m b) -> Unfold m a b
229+fromStream1 f = Unfold streamStep (return . D.toStreamD . f)
230+
231+-- | Convert a two argument stream generator function into an 'Unfold'. Note
232+-- that a stream converted to an 'Unfold' may not be as efficient as an
233+-- 'Unfold' in some situations.
234+--
235+-- /Internal/
236+fromStream2 :: (K.IsStream t, Monad m)
237+ => (a -> b -> t m c) -> Unfold m (a, b) c
238+fromStream2 f = Unfold streamStep (\(a, b) -> return $ D.toStreamD $ f a b)
239+
198240-------------------------------------------------------------------------------
199241-- Unfolds
200242-------------------------------------------------------------------------------