views:

98

answers:

3

Is there an online tool for adding parentheses to simple math equations? For example,

a + b * c

into

a + (b * c)

Those who paid more attention in math class might be able to tackle order of operations for huge equations in their head, but I could often use some help (and verification of my thinking).

I often encounter other people's libraries having equations and functions I need for my code, and this would be kind of helpful for debugging and understanding.

I was hoping Wolfram Alpha would do this, but the output is not easy to plug back into most programming languages e.g. a + (bc)

A: 

this algorithm does more or less what you want, given this is to help you parse the expression not the compiler/interpreter you could simplify it slightly if you are happy that + and - have unary operators as well as binary. as for doing it online ? you'd have to do that yourself. personally id be tempted to write it as an editor macro if i felt i needed it.

jk
+1  A: 

There is a nice roll-your-own online parser site called PEG.js. I used it to create this parenthesizer. Check it out. It currently only handles +,-,*,/, but it should be easy to add more.

brainjam
A: 

A language like SML will offer a particularly general solution to parse arbitrary operators with arbitrary operators with abritrary precedences. In the SML shell, for example, enter

datatype ty = + of ty * ty | * of ty * ty | <& of ty * ty | I of int;
infix <& 9; (*Gives our new crazy op a high priority*)

If you then need text output something like this will do it:

fun pr (a*b) =(print"(";pr a;print"*";pr b;print")")
  | pr (a<&b)=(print"(";pr a;print"+";pr b;print")")
  | pr (I a) =print (Int.toString a);

It will then parse anything you enter into the tree you want. There are not that many languages that have built-in support to add new infix operators like that. You would have to use libraries or string parsers otherwise.

I don't that will help you, but it is the coolest solution (as is almost anything that uses cool languages like SML).

Nicholas Wilson