@@ -346,6 +346,13 @@ mapMStep f res =
346346 Partial s -> pure $ Partial s
347347 Done b -> Done <$> f b
348348
349+-- | If 'Partial' then map the state, if 'Done' then call the next step.
350+{-# INLINE chainStepM #-}
351+chainStepM :: Applicative m =>
352+ (s1 -> m s2) -> (a -> m (Step s2 b)) -> Step s1 a -> m (Step s2 b)
353+chainStepM f _ (Partial s) = Partial <$> f s
354+chainStepM _ g (Done b) = g b
355+
349356------------------------------------------------------------------------------
350357-- The Fold type
351358------------------------------------------------------------------------------
@@ -668,43 +675,34 @@ data SeqFoldState sl f sr = SeqFoldL !sl | SeqFoldR !f !sr
668675-- @since 0.8.0
669676--
670677{-# INLINE serialWith #-}
671−serialWith :: Monad m => (a -> b -> c) -> Fold m x a -> Fold m x b -> Fold m x c
678+serialWith :: Monad m =>
679+ (a -> b -> c) -> Fold m x a -> Fold m x b -> Fold m x c
672680serialWith func (Fold stepL initialL extractL) (Fold stepR initialR extractR) =
673681 Fold step initial extract
674682
675683 where
676684
677− initial = do
678− resL <- initialL
679− case resL of
680− Partial sl -> return $ Partial $ SeqFoldL sl
681− Done bl -> do
682− resR <- initialR
683− return $ bimap (SeqFoldR (func bl)) (func bl) resR
685+ {-# INLINE runR #-}
686+ runR action f = bimap (SeqFoldR f) f <$> action
684687
685− step (SeqFoldL st) a = do
686− r <- stepL st a
687− case r of
688− Partial s -> return $ Partial (SeqFoldL s)
689− Done b -> do
690− res <- initialR
691− return $ bimap (SeqFoldR (func b)) (func b) res
692− step (SeqFoldR f st) a = do
693− r <- stepR st a
694− return
695− $ case r of
696− Partial s -> Partial (SeqFoldR f s)
697− Done b -> Done (f b)
688+ {-# INLINE runL #-}
689+ runL action = do
690+ resL <- action
691+ chainStepM (return . SeqFoldL) (runR initialR . func) resL
692+
693+ initial = runL initialL
694+
695+ step (SeqFoldL st) a = runL (stepL st a)
696+ step (SeqFoldR f st) a = runR (stepR st a) f
698697
699698 extract (SeqFoldR f sR) = fmap f (extractR sR)
700699 extract (SeqFoldL sL) = do
701700 rL <- extractL sL
702701 res <- initialR
703− case res of
704− Partial sR -> do
705− rR <- extractR sR
706− return $ func rL rR
707− Done rR -> return $ func rL rR
702+ fmap (func rL)
703+ $ case res of
704+ Partial sR -> extractR sR
705+ Done rR -> return rR
708706
709707{-# ANN type Step Fuse #-}
710708data SeqFoldState_ sl sr = SeqFoldL_ !sl | SeqFoldR_ !sr