on master help sign in
Add a rollingMapM fold
commit6d247913c1f7a81ad2c1917c7c29c72357a58c2a authorHarendra Kumar <harendra@composewell.com> dateThu 21 Apr 2022, 14:33 (4 years ago) parent8569fdd
1 file changed+24
core/src/Streamly/Internal/Data/Fold.hs+24
core/src/Streamly/Internal/Data/Fold.hs+24
@@ -65,6 +65,7 @@ module Streamly.Internal.Data.Fold
6565 , rollingHashWithSalt
6666 , rollingHashFirstN
6767 -- , rollingHashLastN
68+ , rollingMapM
6869
6970 -- *** Saturating Reducers
7071 -- | 'product' terminates if it becomes 0. Other folds can theoretically
@@ -845,6 +846,29 @@ rollingHash = rollingHashWithSalt defaultSalt
845846rollingHashFirstN :: (Monad m, Enum a) => Int -> Fold m a Int64
846847rollingHashFirstN n = take n rollingHash
847848
849+-- | Apply a function on every two successive elements of a stream. The first
850+-- argument of the map function is the previous element and the second argument
851+-- is the current element. When processing the very first element in the
852+-- stream, the previous element is 'Nothing'.
853+--
854+-- /Pre-release/
855+--
856+{-# INLINE rollingMapM #-}
857+rollingMapM :: Monad m => (Maybe a -> a -> m b) -> Fold m a b
858+rollingMapM f = Fold step initial extract
859+
860+ where
861+
862+ -- XXX We need just a postscan. We do not need an initial result here.
863+ -- Or we can supply a default initial result as an argument to rollingMapM.
864+ initial = return $ Partial (Nothing, error "Empty stream")
865+
866+ step (prev, _) cur = do
867+ x <- f prev cur
868+ return $ Partial (Just cur, x)
869+
870+ extract = return . snd
871+
848872------------------------------------------------------------------------------
849873-- Monoidal left folds
850874------------------------------------------------------------------------------