A RPN Calculator in F#
While continuing my journey in F#, after playing with Project Eulero problems for a few weeks, I have come across another excellent excercise site which goes under the name of Programming Praxis.
The first exercise requires to implement a simple calculator using Reverse Polish Notation (RPN).
Here follows a simple solution to the problem. Operands are pushed onto the stack until an operator is found: at that point the last two operands are popped from the stack, the operator is applied to them and the result is pushed back on the stack.
- We first define a simple function to check whether a given string is to be interpreted as an arithmetic operand. As you can see, we only support basic operators, nothing too fancy.
- We then define a function which takes a double, a string (representing an operator) and another double, and returns the result of applying the given operator to the two numbers.
- The
proc
function takes a string, which represent either an operand or an operator, and a stack of operands.If the item contained in the string is an operator, two operands are popped from the stack: the first pop is for the right side operand and the second pop is for the left operand; hence, the operator is applied to the two operands and the result is pushed back onto the stack.
Otherwise, if it's an operand, it's first converted from the string format and pushed onto the stack.
- Finally, the entrance point to the program is defined with the
evaluate
function, which- accepts a string containing the overall expression (such as "1 2 + 4 / 5 * 6 -")
- splits the string into an array of token strings
- feed each token into the
proc
function - finally pops the stack with the last operand to yield the result of the operation.
Leave a Comment