2
votes

When using alternative parsers, is there an option to get which parser matched input.

My input string can be like below format

{firstPart_number} {secondPart_operator_symbol} {thirdPart}

Here firstPart is always number, second part is alternative parser to parse operator and thirdPart is also alternative (of number, list of string).

sample input

 1 + 2 
 5 * 3 
 1 in {2,45,6}

Since my discriminated unions are of different types, I want to know which parser matched input so that based on that parser I can create instance of my discriminate union type?

How to handle this situation in FParsec, where my first part is same across parsers but second and third parsers are different and based on that instantiate Type using |>>

1
Could you show us a code snippet (not the whole code, just a relevant short snippet) so we can see how you're hooking up your alternative parsers? It's hard to picture your code from just the description you've given. - rmunn
One thought I had was that you could have each alternative parser wrapped in a |>> operator. Something like let pOperator = (pstr "*" |>> OpTimes) <|> (pstr "+" |>> OpPlus) <|> (pstr "in" |>> OpIn). But I'd like to see your code so I can give better suggestions. - rmunn

1 Answers

0
votes

my present problem was solved using attempt parser with alternatives. attempt will backtrack if it doesn't match and next alternative parser will parse input again and match