on master help sign in
Add takeWhile1
commit3622e37b4effdbac49f9dbe2ea6df887504c8684 authorHarendra Kumar <harendra@composewell.com> dateThu 9 Apr 2020, 13:44 (7 years ago) parent5f4de86
1 file changed+33
src/Streamly/Internal/Data/Parser.hs+33
src/Streamly/Internal/Data/Parser.hs+33
@@ -67,6 +67,7 @@ module Streamly.Internal.Data.Parser
6767 -- Grab a sequence of input elements by inspecting them
6868 , takeWhile
6969 -- , takeWhileBetween
70+ , takeWhile1
7071 , sepBy
7172 , sepByMax
7273 -- , sepByBetween
@@ -400,6 +401,38 @@ takeWhile predicate (Fold fstep finitial fextract) =
400401 then Yield 0 <$> fstep s a
401402 else Stop 1 <$> fextract s
402403
404+-- | Like 'takeWhile' but takes at least one element otherwise fails.
405+--
406+-- /Internal/
407+--
408+{-# INLINE takeWhile1 #-}
409+takeWhile1 :: MonadThrow m => (a -> Bool) -> Fold m a b -> Parser m a b
410+takeWhile1 predicate (Fold fstep finitial fextract) =
411+ Parser step initial extract
412+
413+ where
414+
415+ initial = return Nothing
416+
417+ step Nothing a =
418+ if predicate a
419+ then do
420+ s <- finitial
421+ r <- fstep s a
422+ return $ Yield 0 (Just r)
423+ else return $ Error "takeWhile1: empty"
424+ step (Just s) a =
425+ if predicate a
426+ then do
427+ r <- fstep s a
428+ return $ Yield 0 (Just r)
429+ else do
430+ b <- fextract s
431+ return $ Stop 1 b
432+
433+ extract Nothing = throwM $ ParseError "takeWhile1: end of input"
434+ extract (Just s) = fextract s
435+
403436-- | Collect stream elements until an element succeeds the predicate. Drop the
404437-- element on which the predicate succeeded. The succeeding element is treated
405438-- as an infix separator which is dropped from the output.