on master help sign in
Add "maybe" fold
commitfc8670670e869d0b5fa812eb471383b00016e491 authorHarendra Kumar <harendra@composewell.com> dateSun 29 May 2022, 16:39 (4 years ago) parentb3c6948
1 file changed+14−4
core/src/Streamly/Internal/Data/Fold.hs+14−4
core/src/Streamly/Internal/Data/Fold.hs+14−4
@@ -90,12 +90,14 @@ module Streamly.Internal.Data.Fold
9090 , toMap
9191
9292 -- ** Terminating Folds
93− -- Element folds
93+ -- Element folds. Terminate after inspecting one element. All these can be
94+ -- implemented in terms of the 'maybe' fold.
9495 , head
9596 , one
9697 , null
98+ , maybe
9799
98− -- Sequence folds
100+ -- Sequence folds. Terminate after inspecting a sequence of elements.
99101 , drainN
100102 -- , lastN
101103 -- , (!!)
@@ -324,7 +326,7 @@ import Prelude hiding
324326 , notElem, maximum, minimum, head, last, tail, length, null
325327 , reverse, iterate, init, and, or, lookup, (!!)
326328 , scanl, scanl1, replicate, concatMap, mconcat, foldMap, unzip
327− , span, splitAt, break, mapM, zip)
329+ , span, splitAt, break, mapM, zip, maybe)
328330import Streamly.Internal.Data.Fold.Type
329331
330332-- $setup
@@ -1021,6 +1023,14 @@ genericIndex i = mkFold step (Partial 0) (const Nothing)
10211023index :: Monad m => Int -> Fold m a (Maybe a)
10221024index = genericIndex
10231025
1026+-- | Map a 'Maybe' returning function on the next element in the stream.
1027+--
1028+-- /Pre-release/
1029+--
1030+{-# INLINE maybe #-}
1031+maybe :: Monad m => (a -> Maybe b) -> Fold m a (Maybe b)
1032+maybe f = mkFold_ (const (Done . f)) (Partial Nothing)
1033+
10241034-- Naming notes:
10251035--
10261036-- "head" and "next" are two alternative names for the same API. head sounds
@@ -1052,7 +1062,7 @@ index = genericIndex
10521062--
10531063{-# INLINE one #-}
10541064one :: Monad m => Fold m a (Maybe a)
1055−one = mkFold_ (const (Done . Just)) (Partial Nothing)
1065+one = maybe Just
10561066
10571067-- | Extract the first element of the stream, if any.
10581068--