1

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.

Manishearth
  • 14,882
  • 8
  • 59
  • 76
Chris
  • 7,270
  • 19
  • 66
  • 110

2 Answers2

2

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.

btilly
  • 43,296
  • 3
  • 59
  • 88
0

Simple ES6 implementation:

const postfix = input => input.split(' ').reduce((result, token) => 
 isNaN(token)
  ? [ eval(`${result.shift()}${token}${result.shift()}`), ...result ] 
  : [ token, ...result ]
, [])[0];
tnt-rox
  • 5,400
  • 2
  • 38
  • 52