Infix Calculator in Clojure
Following on from my previous post, I have continued my exploration into Clojure by implementing a simple infix calculator - using the Shunting Yard algorithm and RPN evaluation. The documented implementation is split into three distinct parts of which I will describe piece-by-piece, before composing them together to result in the final calculator.
The first problem to solve is to correctly split up the supplied infix expression into the tokenized output. The implementation below ‘reduces’ over each of the characters in the expression producing an output list which correctly merges co-located digits.
Shunting Yard Algorithm
Looking at the implementation above you will notice that we have been able to use a two element vector to represent the output notation and stack which are then joined at the end to return the final output.
With the expression now represented in RPN we can use the following implementation to evaluate this token sequence, returning the final result.
With all the pieces now created, we can compose the calculator function from these constituent parts. We are able to document the transformation from expression to result using the following ‘log’ function, which can be thought of as an identity function with the side-effect of printing out the supplied parameter.
With this function now declared we can create the ‘calc’ function which is a composition of the implemented functions above.