2

I am now in the midst of making a simple bytecode interpreter that uses RPN for expression notation and really postfix notation for anything, but now I've come to the question which is: can short circuit evaluation actually be used on postfix expressions? For example when evaluating the expression (false && (factorial(7) > factorial(5))) C++ knows the result of the && operator on the two operands evaluates to false before it even gets to the second operand, since (false && anything) is always equal to false. Now when you put this in RPN, you get (false (7 factorial 5 factorial >) &&).

I wanted to build an efficient RPN expression parser, so the problem is this: how do I make an efficient RPN expression parser with short circuit evaluation?

J.J. Hakala
  • 6,136
  • 6
  • 27
  • 61
  • You write code. We are not here to design your system for you, or teach you how to design it. – Marc B Jul 22 '16 at 16:42
  • @MarcB Thanks for the information I guess. Anyway I did get a useful answer, so yeah. – Imanuel Habekotte Jul 22 '16 at 17:46
  • RPN and postfix notation are the same thing, not two different things. You don't build RPN parsers into interpreters. The input is already parsed and can be processed linearly. If you want short-circuit evaluation you need to introduce branches. – user207421 Feb 26 '17 at 23:45

1 Answers1

2

You would evaluate an RPN expression in two phases.

Phase 1: parse the RPN, and construct a tree representation of the RPN. So, in this tree, for example, the && node has two children nodes, for each half of the expression. Constructing this tree is a nearly identical process as evaluating the RPN, except for the evaluating part, which gets replaced by the operation of constructing a new node, and linking its child nodes to their new parent node, then pushing the parent node back on the RPN evaluation stack.

Phase 2: evaluate the constructed tree, using recursive descent. At this point, short-circuit evaluation becomes trivial: evaluate the left-hand child of a &&, then decide whether you actually want to evaluate the right-hand child.

Ditto for the || node, etc...

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • Thanks this is perfect! :) – Imanuel Habekotte Jul 22 '16 at 17:47
  • Question: would it be different if I instead switch to using PN instead of RPN? – Imanuel Habekotte Jul 23 '16 at 13:43
  • 1
    The first phase would be different, of course. Different logic to construct the tree. Alternatively, the PN parser could be written so that it carries a "ignore" flag, where it only parses and swallows the input, without evaluating it, recursively passing the flag down; with the `&&` and `||` operators setting the flag for the right-hand side evaluation, if the left-hand side evaluation made it unnecessary for the right-hand side to be evaluated. – Sam Varshavchik Jul 23 '16 at 13:47