I have a bunch of boolean expressions written in prefix notation (also called Polish notation). Nested expressions in this format are very easy to evaluate (see the algorithm in the Wikipedia article).
The algorithm given on the Wikipedia page, however, does not do short-circuiting (when it evaluates and f() g(), it does not skip the evaluation of g() if f() is false). Is there any way to modify the algorithm to include short-circuiting?
You could use the same algorithm to build an expression tree: instead of evaluating
operand1 operator operand2, create a node withoperand1andoperand2as children, andoperatoras parent.Once you have the tree, you can evaluate it (top to bottom). You can short-circuit the evaluation by not evaluating one of the children (for example if the left child evaluates to
Falseand the operator isand).You’ll notice that the given algorithm is equivalent to evaluation from bottom to top. While this is simple (and saves memory), you cannot apply short-circuiting because you never know if the branch you’re in should even be evaluated.