on master help sign in
Generalize either unfold and add nil unfold
commit24277153d0c993ac359980480360e69671c7c8f0 authorHarendra Kumar <harendra@composewell.com> dateSat 31 Dec 2022, 11:43 (4 years ago) parent1b00239
1 file changed+23−11
core/src/Streamly/Internal/Data/Unfold.hs+23−11
core/src/Streamly/Internal/Data/Unfold.hs+23−11
@@ -126,6 +126,7 @@ module Streamly.Internal.Data.Unfold
126126 , function
127127 , identity
128128 , nilM
129+ , nil
129130 , consM
130131
131132 -- ** From Values
@@ -292,6 +293,7 @@ import qualified Streamly.Internal.Data.Fold.Type as FL
292293import qualified Streamly.Internal.Data.Stream.StreamD.Type as D
293294import qualified Streamly.Internal.Data.Stream.StreamK.Type as K
294295import qualified Streamly.Internal.Data.Stream.Type as Stream
296+import qualified Prelude
295297
296298import Streamly.Internal.Data.Unfold.Enumeration
297299import Streamly.Internal.Data.Unfold.Type
@@ -448,25 +450,30 @@ foldMany (Fold fstep initial extract) (Unfold ustep inject1) =
448450-- Either
449451-------------------------------------------------------------------------------
450452
451−-- | Make an unfold operate on values wrapped in an @Either a a@ type. 'Right
452−-- a' translates to 'Right b' and 'Left a' translates to 'Left b'.
453+-- | Choose left or right unfold based on an either input.
453454--
454−-- /Internal/
455+-- /Pre-release/
455456{-# INLINE_NORMAL either #-}
456−either :: Applicative m => Unfold m a b -> Unfold m (Either a a) (Either b b)
457−either (Unfold step1 inject1) = Unfold step inject
457+either :: Applicative m =>
458+ Unfold m a c -> Unfold m b c -> Unfold m (Either a b) c
459+either (Unfold stepL injectL) (Unfold stepR injectR) = Unfold step inject
458460
459461 where
460462
461− inject (Left a) = (, Left) <$> inject1 a
462− inject (Right a) = (, Right) <$> inject1 a
463+ inject (Left x) = Left <$> injectL x
464+ inject (Right x) = Right <$> injectR x
463465
464466 {-# INLINE_LATE step #-}
465− step (st, f) = do
467+ step (Left st) = do
466468 (\case
467− Yield x s -> Yield (f x) (s, f)
468− Skip s -> Skip (s, f)
469− Stop -> Stop) <$> step1 st
469+ Yield x s -> Yield x (Left s)
470+ Skip s -> Skip (Left s)
471+ Stop -> Stop) <$> stepL st
472+ step (Right st) = do
473+ (\case
474+ Yield x s -> Yield x (Right s)
475+ Skip s -> Skip (Right s)
476+ Stop -> Stop) <$> stepR st
470477
471478-- postscan2 :: Monad m => Refold m a b c -> Unfold m a b -> Unfold m a c
472479
@@ -616,6 +623,11 @@ nilM f = Unfold step pure
616623 {-# INLINE_LATE step #-}
617624 step x = f x $> Stop
618625
626+-- | An empty stream.
627+{-# INLINE nil #-}
628+nil :: Applicative m => Unfold m a b
629+nil = Unfold (Prelude.const (pure Stop)) pure
630+
619631-- | Prepend a monadic single element generator function to an 'Unfold'. The
620632-- same seed is used in the action as well as the unfold.
621633--