I am trying to define my grammar as a discriminated union. It has two possible types: int and datetime and mathemetical operators of Add and Mul.
Add works on int and datetime (as add days in int)
Mul works only on int and not on datetime
Grammar can be recursive
My grammar looks like
type MyExpression =
|Integer of int
|Date of datetime
|Add of MyExpression * MyExpression
|Mul of MyExpression * MyExpression
I have written a parser (fparsec) that can parse text in my grammar, but I am not sure how to handle the condition that Mul can be recursive but only on Integer.
Is there an option to define this restriction on my MyExpression type or do I have to handle this in my parsed input?
The design suggested by Asti would also be my first choice. Depending on your requirements, that may be all you need.
It does, however, also enable you to compile an expression like
which is probably not what you want.
Alternatively, you could model expressions like this:
This is clearly a more verbose type definition, but it does embody the rule that an expression can contain leaf nodes of either integers or
DateTimevalues, and no other values - if that's the rule you want to enforce.I'm not claiming that this is better; I'm only supplying an alternative.
Usage: