@@ -68,6 +68,7 @@ module Streamly.Internal.Data.Stream.StreamK.Type
6868 , concatMapBy
6969 , concatMap
7070 , bindWith
71+ , concatPairsWith
7172 , apWith
7273 , apSerial
7374 , apSerialDiscardFst
@@ -1118,6 +1119,51 @@ concatMap_ f xs = buildS
11181119 (\c n -> foldrSShared (\x b -> foldrSShared c b (unShare $ f x)) n xs)
11191120-}
11201121
1122+-- | See 'Streamly.Internal.Data.Stream.IsStream.concatPairsWith' for
1123+-- documentation.
1124+--
1125+{-# INLINE concatPairsWith #-}
1126+concatPairsWith
1127+ :: IsStream t
1128+ => (t m b -> t m b -> t m b)
1129+ -> (a -> t m b)
1130+ -> t m a
1131+ -> t m b
1132+concatPairsWith combine f = go Nothing
1133+
1134+ where
1135+
1136+ go Nothing stream =
1137+ mkStream $ \st yld sng stp ->
1138+ let foldShared = foldStreamShared st yld sng stp
1139+ single a = foldShared $ unShare (f a)
1140+ yieldk a r = foldShared $ go (Just a) r
1141+ in foldStream (adaptState st) yieldk single stp stream
1142+ go (Just a1) stream =
1143+ mkStream $ \st yld sng stp ->
1144+ let foldShared = foldStreamShared st yld sng stp
1145+ stop = foldShared $ unShare (f a1)
1146+ single a = foldShared $ unShare (f a1) `combine` f a
1147+ yieldk a r =
1148+ foldShared
1149+ $ concatPairsWith combine
1150+ (\(x,y) -> combine (unShare x) y)
1151+ $ (f a1, f a) `cons` makePairs Nothing r
1152+ in foldStream (adaptState st) yieldk single stop stream
1153+
1154+ makePairs Nothing stream =
1155+ mkStream $ \st yld sng stp ->
1156+ let foldShared = foldStreamShared st yld sng stp
1157+ single a = sng (f a, nil)
1158+ yieldk a r = foldShared $ makePairs (Just a) r
1159+ in foldStream (adaptState st) yieldk single stp stream
1160+ makePairs (Just a1) stream =
1161+ mkStream $ \st yld sng _ ->
1162+ let stop = sng (f a1, nil)
1163+ single a = sng (f a1, f a)
1164+ yieldk a r = yld (f a1, f a) (makePairs Nothing r)
1165+ in foldStream (adaptState st) yieldk single stop stream
1166+
11211167instance Monad m => Applicative (Stream m) where
11221168 {-# INLINE pure #-}
11231169 pure = yield