RPN & Functions
I wrote a program a while back to take an Infix expression ("2 + 2 * 3") and convert it to Postfix notation (Reverse Polish) and evaluate it. Worked like a charm, and can handle things as complex as "2 * (4 + 5 / 5 * sin(490.333))"
Now what I'm wondering is if there is any way to implement functions with a variable number of arguments. The only bright ideas I've had so far is "don't" and to keep the first thing on the stack as a "# of parameters", for those functions that need them. So, say log could take either 1 or 2 parameters, and took the form log(number, [base]), where base is the optional parameter. So far, I suppose I could write:
number 1 log
base number 2 log
But keeping the # of arguments like that seems like a kludge, especially if I ever want to actually use the RPN side as a human, and not just for evaluating the results of a infix conversion.
Any other ideas on how to implement this? Are there any RPN calculators out there with variable-number of argument functions - if so, how do they do it?
(Reverse Polish Notation (RPN), or postfix notation)
The function could perhaps just pop off as many arguments as it needs. If the function doesn't know how many parameters it needs, you have no choice but passing the number of arguments anyway, or perhaps an end-of-arguments sentinel.
I'm thinking that it should be the parser which reads either
and always pushes the default value onto the stack if none is specified.
Then when the evaluate comes along, the correct number of parameters are always present.
But I think he's referring to functions that can take any amount of parameters, like
function max(parameter_bundle numbers)
result = first of numbers
for each n in numbers except first do
if n greater than result then result = n
end with result
max(1, 2, 3, 4, 5, 6, 7, 8) -> 8