Parenthesize expressions.

1.3k Views Asked by At

Can someone tell me how to add parenthesis to this expression

$a + b \cdot c \cdot d + e$.

where $a,b,c,d,e$ are algebraic variables, where addition and multiplication is as usual there. :-)

If you have any other complicated examples please explain them to me and if possible, mention the core concept which would enable me to parenthesize any complex expression.

3

There are 3 best solutions below

1
On BEST ANSWER

The operator $"+"$ has a lower priority than the multiplication operator, so you first do the multiplication and the the sum, and the experssion in the parenthesis has high priority so you have to write in the parenthesis the expression with the multiplication operator: $$a+(b \cdot c \cdot d) +e$$ or $$a+((b \cdot c) \cdot d)+e$$

0
On

(a+b)⋅c⋅(d+e)

or

a+(b⋅c⋅d)+e

or

(a+b⋅c)⋅d+e

or

a+b⋅(c⋅d+e)

?

3
On

If @mvw 's comment is correct, then, assuming LR, you'll parse this as $$((a+( ( b \cdot c) \cdot d) ) + e)$$ And a proper tag, if it existed, would be "recursive descent parsing" because this isn't really RegEx analysis.

If this is just standalone evaluation of simple expressions like this, you're fine using LR and top-down descent. If it is part of a larger parser, you might want to consider flattening your tree by using an operator precedence table and Dijkstra's shunting algorithm for binary expression parsing instead. The wiki page has a detailed example. For easy cases, the algorithm is straightforward; handling assignment operations ("=") and such takes a bit more thought as you must flip parsing direction.