Search code examples
c#stackexpressionpostfix-notation

how to build and eval a postfix stack for expressions that contain functions with optional parameters


For example:

3 + 4 * max(2, avg(6, 8, 2, 4,...), 6, ...)

My first thought is to create a special token that is the count of the parameters and push it into the stack when ")" is encountered. But I am not sure how to keep count when the parameters themselves could be functions with parameters.


Solution

  • I solved the problem by slightly modifying the Shunting-yard algorithm and inserting a special token (called @) to the output stack right after any prefix operations.

    For example: 4 * max(2, avg(6, 8), 32) + 3 will generate an output stack of: + 3 * Max 32 Avg 8 6 @ 2 @ 4

    When evaluating this stack from left to right, function Avg will know to stop popping operand when it seems the first @ token, so will the function max.