on master help sign in
Add 'next' to Parsers
commitd70b57c03982d290fdde001d22685c49bb1bb876 authorJulian Ospald <hasufell@posteo.de> dateSun 24 Oct 2021, 18:35 (5 years ago) parent13e3129
3 files changed+38
src/Streamly/Internal/Data/Parser.hs+10 src/Streamly/Internal/Data/Parser/ParserD.hs+13 test/Streamly/Test/Data/Parser.hs+15
src/Streamly/Internal/Data/Parser.hs+10
@@ -66,6 +66,7 @@ module Streamly.Internal.Data.Parser
6666 , peek
6767 , eof
6868 , satisfy
69+ , next
6970 , maybe
7071 , either
7172
@@ -342,6 +343,15 @@ eof = K.toParserK D.eof
342343satisfy :: MonadCatch m => (a -> Bool) -> Parser m a a
343344satisfy = K.toParserK . D.satisfy
344345
346+-- | Return the next element of the input. Returns 'Nothing'
347+-- on end of input. Also known as 'head'.
348+--
349+-- /Pre-release/
350+--
351+{-# INLINE next #-}
352+next :: MonadCatch m => Parser m a (Maybe a)
353+next = K.toParserK D.next
354+
345355-- | Map a 'Maybe' returning function on the next element in the stream. The
346356-- parser fails if the function returns 'Nothing' otherwise returns the 'Just'
347357-- value.
src/Streamly/Internal/Data/Parser/ParserD.hs+13
@@ -33,6 +33,7 @@ module Streamly.Internal.Data.Parser.ParserD
3333 , peek
3434 , eof
3535 , satisfy
36+ , next
3637 , maybe
3738 , either
3839
@@ -311,6 +312,18 @@ satisfy predicate = Parser step initial extract
311312
312313 extract _ = throwM $ ParseError "satisfy: end of input"
313314
315+-- | See 'Streamly.Internal.Data.Parser.satisfy'.
316+--
317+-- /Pre-release/
318+--
319+{-# INLINE next #-}
320+next :: MonadCatch m => Parser m a (Maybe a)
321+next = Parser step initial extract
322+ where
323+ initial = pure $ IPartial ()
324+ step _ a = pure $ Done 0 (Just a)
325+ extract _ = pure Nothing
326+
314327-- | See 'Streamly.Internal.Data.Parser.maybe'.
315328--
316329-- /Pre-release/
test/Streamly/Test/Data/Parser.hs+15
@@ -155,6 +155,19 @@ satisfy =
155155 where
156156 predicate = (>= mid_value)
157157
158+nextPass :: Property
159+nextPass =
160+ forAll (chooseInt (1, max_value)) $ \int ->
161+ property (case S.parse P.next (S.fromList [int]) of
162+ Right (Just i) -> i == int
163+ _ -> False)
164+
165+next :: Property
166+next =
167+ property (case S.parse P.next (S.fromList []) of
168+ Right Nothing -> True
169+ _ -> False)
170+
158171-- Sequence Parsers Tests
159172takeBetweenPass :: Property
160173takeBetweenPass =
@@ -745,6 +758,8 @@ main =
745758 prop "eof pass on []" eofPass
746759 prop "eof fail on non-empty list" eofFail
747760 prop "first element exists and >= mid_value" satisfyPass
761+ prop "next pass on [Int]" nextPass
762+ prop "next fail on []" next
748763 prop "check first element exists and satisfies predicate" satisfy
749764
750765 describe "test for sequence parser" $ do