c# - Shunting-Yard Validate Expression -
we use shunting-yard algorithm evaluate expressions. can validate expression applying algorithm. fails if there missing operands, miss-matched parenthesis, , other things. shunting-yard algorithm has larger supported syntax human readable infix. example,
1 + 2 + 1 2 1 2 +
are acceptable ways provide '1+2' input shunting-yard algorithm. '+ 1 2' , '1 2 +' not valid infix, standard shunting-yard algorithm can handle them. algorithm not care order, applies operators order of precedence grabbing 'nearest' operands.
we restrict our input valid human readable infix. looking way either modify shunting-yard algorithm fail non-valid infix or provide infix validation prior using shunting-yard.
is aware of published techniques this? must support both basic operator, custom operators, brackets, , functions (with multiple arguments). haven't seen works more basic operators online.
thanks
a nice discussion on shunting yard algorithms http://www.engr.mun.ca/~theo/misc/exp_parsing.htm algorithm presented there uses key idea of operator stack has grammar know should expected next. has 2 main functions e()
expects expression , p()
expecting either prefix operator, variable, number, brackets , functions. prefix operators bind tighter binary operators want deal of first.
if p stands prefix sequence , b binary operator expression of form
p b p b p
i.e. either expecting a prefix sequence or binary operator. formally grammar is
e -> p (b p)*
and p be
p -> -p | variable | constant | etc.
this translates psudocode
e() { p() while next token binary op: read next op push onto stack , shunting yard logic p() if tokens remain report error pop remaining operators off stack } p() { if next token constant or variable: add output else if next token unary minus: push uminus onto operator stack p() }
you can expand handle other unary operators, functions, brackets, suffix operators.
Comments
Post a Comment