Saturday, January 9, 2016

TrainShunting

For ages now I've been trying to implement the Shunting Yard Algorithm to take an expression and evaluate it. Yesterday I finally did it! I completed an iterative Shunting Yard Algorithm along with an evaluation function. The current calculator application is just using the built in javascript eval() function, but now that my shunting yard algo is finished I can use that!

The reason my algorithm is special is that it doesn't just return the prefix statement, but also returns the operator stack and output stack after each pass through the loop! This was actually a little tricky because I needed to make copies of the array at each stage rather than just make a reference to the array. If I had not used Array.from() to make a copy at each stage, I would end up with an array of references to the same object. In other words I would end up with a javascript object containing the final prefix expression, an array of multiple copies of the final prefix expression, and an array of empty arrays.

Another problem I ran into was that, since I was doing this algorithm so infrequently, I never actually took the time out to learn it. I was trying to implement it from pure pseudo-code rather than understand what was actually happening. Understanding what was happening wasn't easy either though, I had never heard of operator associativity or precedence (maybe they're worth a short post in and of themselves). Once I finally had a grasp on it thought, the implementation was fast.

One improvement I want to make is to my evaluate function. I think there must be a way to evaluate the prefix expression recursively (like a recursive in order tree traversal), but right now I'm evaluating it iteratively.

Here's the code, it's got a lot of cleaning up and commenting to do, but what I've got now is in functioning order. Also notice that it currently doesn't handle sin, cos, tan functions.

No comments:

Post a Comment