on master help sign in
Add takeWhile1
3622e37Harendra Kumar
src/Streamly/Internal/Data/Parser.hs+33
@@ -67,6 +67,7 @@ module Streamly.Internal.Data.Parser
67 -- Grab a sequence of input elements by inspecting them
67 -- Grab a sequence of input elements by inspecting them
68 , takeWhile
68 , takeWhile
69 -- , takeWhileBetween
69 -- , takeWhileBetween
70+ , takeWhile1
70 , sepBy
71 , sepBy
71 , sepByMax
72 , sepByMax
72 -- , sepByBetween
73 -- , sepByBetween
@@ -400,6 +401,38 @@ takeWhile predicate (Fold fstep finitial fextract) =
400 then Yield 0 <$> fstep s a
401 then Yield 0 <$> fstep s a
401 else Stop 1 <$> fextract s
402 else Stop 1 <$> fextract s
402
403
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+
403-- | Collect stream elements until an element succeeds the predicate. Drop the
436-- | Collect stream elements until an element succeeds the predicate. Drop the
404-- element on which the predicate succeeded. The succeeding element is treated
437-- element on which the predicate succeeded. The succeeding element is treated
405-- as an infix separator which is dropped from the output.
438-- as an infix separator which is dropped from the output.