Return a single error from Parser.Advanced.oneOf?

I’ve been playing around with elm/parser’s Parser.Advanced and trying to figure out how to build up some good error messages.

Here’s a parser that parses either an integer or a comma:

import Parser.Advanced as Parser

type Context 
    = ParserContext

type Problem
    = ExpectingInt
    | ExpectingComma

type Value
    = VInt Int
    | VComma

intOrComma : Parser.Parser Context Problem Value
intOrComma =
    Parser.oneOf
        [ Parser.int ExpectingInt ExpectingInt
            |> Parser.map VInt
        , Parser.token (Parser.Token "," ExpectingComma)
            |> Parser.map (always VComma)
        ]

When intOrComma fails, it will return 2 dead-ends—one for each potential branch. E.g. here’s the output of an empty string:

Err
  [ { col = 1
    , contextStack = []
    , problem = ExpectingInt
    , row = 1
    }
  , { col = 1
    , contextStack = []
    , problem = ExpectingComma
    , row = 1
    }
  ]

But I really want to provide a single error in this case saying that I expected to see either an int or a comma. Is there a built-in way to do this? Or do I need to look for errors that occur at the same location and combine them myself?

Ellie example here: https://ellie-app.com/7S8s5ZLds3Ka1

I figured out how to do this. :slight_smile:

As the last alternative in the list, use commit to commit to the alternative and then fail with problem.

intOrComma : Parser.Parser Context Problem Value
intOrComma =
    Parser.oneOf
        [ Parser.int ExpectingInt ExpectingInt
            |> Parser.map VInt
        , Parser.token (Parser.Token "," ExpectingComma)
            |> Parser.map (always VComma)
        , Parser.commit ()
            |> Parser.andThen (always <| Parser.problem ExpectingIntOrComma)
        ]
4 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.