I’ve found a way to convert a math expression in infix notation into postfix notation. (http://en.wikipedia.org/wiki/Shunting-yard_algorithm) But then, how should I code to interpret the result expression?
Here’s my idea:
For operand-only expressions:
- Look for a set of objects that follow the format operand-operand-operator.
- Apply the rules of calculation of the operator to the two operands.
- Swap the set of objects into one operand which is the result of the calculation.
For expressions with functions (sine, absolute value, signum…)
- Look for a set of objects that follow the format operand-operand-…-operator.
- The number of operands depends on how many parameters are needed to pass into the function. For example:
- sine – one parameter (the acute angle)
- power – two parameter (n th power of number m)
- 3×3 matrix – nine parameters
- The number of operands depends on how many parameters are needed to pass into the function. For example:
- Do whatever else I mentioned above.
I’m now in a situation that I have not any environment to implement my ideas into a piece of code, thus I can only talk abstract.
Is this idea possible or not? If there can be improvements, please note them. References are also welcomed.
If you are presenting a piece of code, please change the code into words that everyone can understand. For example:
Change:
for (var i:int = 0; i < rpn.length; i++) {
if ("1234567890.".indexOf(rpn[i]) != -1) {
// do something...
}
}
Into:
for every element in the postfix result,
if the element is a number,
do something...
end if
end for
end … is optional, though.
Thanks!
Usually this is the easy part… you just traverse your postfix expression from left to right. Each time you encounter a number, you push it on a stack. Each time you encounter an operator, you pop the relevant number of operands off the stack, compute the result, and push it on the stack.