user10891762
user10891762

Reputation:

Failure handling in a Parser function

I'm learning Parser Combinators with Trifecta library. I was introduced to Alternative typeclass and it's <|> function.

I got a Parser function in my code whose definition is

fractionOrDecimal :: Parser DoubleOrRational
fractionOrDecimal =
        (Left <$> try parseDecimal)                  -- A
    <|> (Right <$> try parseFraction)                -- B
    <|> (fail  "Expected Fraction or Decimal.")      -- Err

which attempts to parse the input as either decimal or fraction and fail if nothing worked. Is this approach correct or should I encode the failure (fail) differently rather than being part of the <|> operation.

Upvotes: 0

Views: 109

Answers (1)

Julia Path
Julia Path

Reputation: 2366

Failure is encoded by the absence of a successful parser. Trifecta will track the expected tokens for you, but you do have to tell it what they are called using <?>. So you would do

fractionOrDecimal :: Parser DoubleOrRational
fractionOrDecimal =
        (Left  <$> try parseDecimal  <?> "Decimal")
    <|> (Right <$> try parseFraction <?> "Fractional")

We now get errors like this:

>>> parseTest fractionalOrDecimal "neither fractional nor decimal"
error: expected: Decimal, Fractional
neither fractional nor decimal<EOF> 
^                       

Upvotes: 4

Related Questions