on master help sign in
Add findIndices fold
ea1b48fHarendra Kumar
core/src/Streamly/Internal/Data/Fold.hs+18−1
@@ -128,9 +128,9 @@ module Streamly.Internal.Data.Fold
128 , mapMaybe
128 , mapMaybe
129 -- , mapMaybeM
129 -- , mapMaybeM
130
130
131− {-
132 -- ** Scanning Filters
131 -- ** Scanning Filters
133 , findIndices
132 , findIndices
133+ {-
134 , elemIndices
134 , elemIndices
135
135
136 -- ** Insertion
136 -- ** Insertion
@@ -893,6 +893,23 @@ findIndex predicate = mkFold step (Partial 0) (const Nothing)
893 then Done $ Just i
893 then Done $ Just i
894 else Partial (i + 1)
894 else Partial (i + 1)
895
895
896+-- XXX If we have a Continue contructor we won't need a Maybe type for the
897+-- scan. The fold will have the ability to skip producing output.
898+--
899+-- | Returns all indices that satisfy the given predicate.
900+--
901+{-# INLINE findIndices #-}
902+findIndices :: Monad m => (a -> Bool) -> Fold m a (Maybe Int)
903+findIndices predicate =
904+ fmap (either (const Nothing) Just) $ foldl' step (Left (-1))
905+
906+ where
907+
908+ step i a =
909+ if predicate a
910+ then Right (either id id i + 1)
911+ else Left (either id id i + 1)
912+
896-- | Returns the first index where a given value is found in the stream.
913-- | Returns the first index where a given value is found in the stream.
897--
914--
898-- > elemIndex a = Fold.findIndex (== a)
915-- > elemIndex a = Fold.findIndex (== a)