on master help sign in
Add "one" fold which is an alias for "head"
commit8230747201060e70b3b7b80ddf32860c9dd03d95 authorHarendra Kumar <harendra@composewell.com> dateWed 18 May 2022, 19:35 (4 years ago) parent2f9709b
1 file changed+38−1
core/src/Streamly/Internal/Data/Fold.hs+38−1
core/src/Streamly/Internal/Data/Fold.hs+38−1
@@ -96,6 +96,7 @@ module Streamly.Internal.Data.Fold
9696 , genericIndex
9797 , index
9898 , head
99+ , one
99100 -- , findM
100101 , find
101102 , lookup
@@ -1010,12 +1011,48 @@ genericIndex i = mkFold step (Partial 0) (const Nothing)
10101011index :: Monad m => Int -> Fold m a (Maybe a)
10111012index = genericIndex
10121013
1014+-- Naming notes:
1015+--
1016+-- "head" and "next" are two alternative names for the same API. head sounds
1017+-- apt in the context of lists but next sounds more apt in the context of
1018+-- streams where we think in terms of generating and consuming the next element
1019+-- rather than taking the head of some static/persistent structure.
1020+--
1021+-- We also want to keep the nomenclature consistent across folds and parsers,
1022+-- "head" becomes even more unintuitive for parsers because there are two
1023+-- possible variants viz. peek and next.
1024+--
1025+-- Also, the "head" fold creates confusion in situations like
1026+-- https://github.com/composewell/streamly/issues/1404 where intuitive
1027+-- expectation from head is to consume the entire stream and just give us the
1028+-- head. There we want to convey the notion that we consume one element from
1029+-- the stream and stop. The name "one" already being used in parsers for this
1030+-- purpose sounds more apt from this perspective.
1031+--
1032+-- The source of confusion is perhaps due to the fact that some folds consume
1033+-- the entire stream and others terminate early. It may have been clearer if we
1034+-- had separate abstractions for the two use cases.
1035+
1036+-- XXX We can possibly use "head" for the purposes of reducing the entire
1037+-- stream to the head element i.e. take the head and drain the rest.
1038+
1039+-- | Take one element from the stream and stop.
1040+--
1041+-- /Pre-release/
1042+--
1043+{-# INLINE one #-}
1044+one :: Monad m => Fold m a (Maybe a)
1045+one = mkFold_ (const (Done . Just)) (Partial Nothing)
1046+
10131047-- | Extract the first element of the stream, if any.
10141048--
1049+-- >>> head = Fold.one
1050+--
10151051-- @since 0.7.0
1052+-- {-# DEPRECATED head "Please use \"one\" instead" #-}
10161053{-# INLINE head #-}
10171054head :: Monad m => Fold m a (Maybe a)
1018−head = mkFold_ (const (Done . Just)) (Partial Nothing)
1055+head = one
10191056
10201057-- | Returns the first element that satisfies the given predicate.
10211058--