0

I have an Attoparsec parser like this:

myParser :: Parser Text
myParser = char '"' *> takeWhile (not . isspace) <* char '"'

I want to make this parser optional so I get a function that returns Just txt if the parser matches and Nothing else, i.e. a function of the signature:

myMaybeParser :: Parser (Maybe Text)

How can I do this?

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
  • 1
    It seems to me that you keep asking questions and accepting your own answers, which by the way are posted at the exact same time of the question. – rubik Dec 07 '15 at 20:56
  • 1
    @rubik Yes, this is a built-in feature of StackOverflow and it is actively encouraged to use it! Please read https://stackoverflow.com/help/self-answer – Uli Köhler Dec 07 '15 at 21:15
  • @rubik Please note that I will happily accept other answers. I had several self-answered questions where someone came up with a better answer and I happily accepted it. – Uli Köhler Dec 07 '15 at 21:16

1 Answers1

1

You can use option and the Applicative instance of Parser for this:

-- Make a parser optional, return Nothing if there is no match
maybeOption :: Parser a -> Parser (Maybe a)
maybeOption p = option Nothing (Just <$> p)

You can then use it like this:

myMaybeParser = maybeOption myParser
Uli Köhler
  • 13,012
  • 16
  • 70
  • 120