I need to write a function that can take an if statement at runtime (eg. user input, or from a data file). Ideally it should be able to solve an expression no less complex than:
a && ( b || !c || ( d && e ) )
I imagine what I need is a recursive function (one that calls itself). Of course, the function needs to return true or false.
Because of the complexity of the example above, the function would need to not only loop through the individual conditions, but understand the operators, know the order in which to evaluate them and preferably prioritise them for speed (eg. in the example, if a is false there is no need to evaluate the rest of the statement).
Does anyone have any ideas?
One solution would be using shunting yard algorithm to convert the expression to RPN, and then evaluate it as RPN (because RPN is much easier to evaluate than infix). The first part, conversion to RPN (in pseudocode):
read_tokenreads a token from input queueoutputinserts a value into output queuepushpushes a value into the stack (you only need one)poppops a value out of a stacktoppeeks the value at the top of the stack without poppingThe RPN evaluation is simpler:
read_token()reads values from the RPN queue generated in previous stepeval(t, val)evaluates unary operatortwith operandvaleval(t, val1, val2)evaluates binary operatortwith operandsval1andval2resultis the final value of the expressionThis simplified algorithm should work if all your operators are left-associative and no functions are used. Note that no recursion is necessary, because we use our own stack implementation.
For examples and more information, see Rosetta Code on Shunting-yard and Rosetta Code on RPN