Evaluating Postfix Notation
-
27-10-2019 - |
Question
I wrote a stack class to evaluate a postfix expression. I understand how to do it except for the order of it. Let's say I have a simple one like:
A B - C +
My only question is, would it be A - B, or B - A? I can't find any resource online that explains that part of evaluation.
Solution
Your operators are just functions. So you can define those functions however you want.
I personally would define - to take two arguments, and subtract the second from the first. This would be consistent with most people's expectations, and also how existing RPN calculators work. See, for instance, http://h41111.www4.hp.com/calculators/uk/en/articles/rpn.html for more on that.
OTHER TIPS
Simple ES6 implementation:
const postfix = input => input.split(' ').reduce((result, token) =>
isNaN(token)
? [ eval(`${result.shift()}${token}${result.shift()}`), ...result ]
: [ token, ...result ]
, [])[0];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow