Add optional

This commit is contained in:
Niklas Larsson 2020-07-05 16:00:29 +02:00
parent 0e51124a43
commit d779c85df4
2 changed files with 14 additions and 1 deletions

View File

@ -122,3 +122,7 @@ takeWhile f = do ls <- many (satisfy f)
export
option : Monad m => a -> ParseT m a -> ParseT m a
option def p = p <|> pure def
export
optional : Monad m => ParseT m a -> ParseT m (Maybe a)
optional p = (p >>= \res => pure $ Just res) <|> pure Nothing

View File

@ -32,6 +32,11 @@ optParser = do res <- option "" (takeWhile isDigit)
string "def"
pure $ res
maybeParser : ParseT IO Bool
maybeParser = do res <- optional (string "abc")
string "def"
pure $ isJust res
main : IO ()
main = do
res <- parseT parseStuff "abcdef"
@ -50,4 +55,8 @@ main = do
showRes res
res <- parseT optParser "def"
showRes res
res <- parseT maybeParser "abcdef"
showRes res
res <- parseT maybeParser "def"
showRes res
pure ()