Search code examples
mathshunting-yardrewriting

Shunting Yard Algorithm with Variables


I'm currently working on a modified version of the Shunting Yard Algorithm that would work with variables, but I cant figure out how to get it to work. For example, I would want the algorithm to re-write 2 * (2x + 5) - 5 to 4x + 5. Any ideas / links to already implemented algorithms that does this already?


Solution

    1. Take the expression: 2 * (2x + 5) - 5
    2. Add the * symbol to make it more understandable for the computer: 2 * (2*x + 5) - 5
    3. Parse it using the Shunting Yard Algorithm, it becomes: 2 2 x * 5 + * 5 - (Each character could be seen as an element of an array).
    4. With the parsed expression, create the binary tree:

    - / \ * 5 / \ 2 + / \ * 5 / \ 2 x 5. Define and apply algebraic rules to the tree. For example, a rule to be able to 'multiply' the 2 node with the 2 * x + 5 subtree.