Skip to content

Swift implementation of the shunting yard algorithm converting infix to postfix notation.

Notifications You must be signed in to change notification settings

mkorsback/ShuntingYard

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swift implementation of the Shunting Yard algorithm.

This is a small example if how to use the shunting yard algorithm to convert expressions written using infix notation to postfix notation (aka Reverse Polish Notation, or RPN).

More information here: https://en.wikipedia.org/wiki/Shunting-yard_algorithm

Example of infix to postfix:

Infix: 2 / 8 - 3 * (15 / 5) ^ 3
Postfix: 2, 8, /, 3, 15, 5, /, 3, ^, *, -

The project also contains an evaluator that performs evaluation of the expression.

Example run:

Expression: 2 / 8 - 3 * (15 / 5) ^ 3
Infix tokens: [2, /, 8, -, 3, *, (, 15, /, 5, ), ^, 3]
Postfix tokens: [2, 8, /, 3, 15, 5, /, 3, ^, *, -]
Result: -80.75

Technical details

Implemented using a Stack and a Queue to stay close to the original algorithm.

100% test coverage because why not. 😎

PEMDAS Support

  • Parentheses
  • Exponents
  • Multiplication
  • Division
  • Addition
  • Subtraction

Current known limitations

  • Only handles integers as input
  • No support for unary operations
  • Doesn't handle non-integer exponents, like 9 ^ (2 / 6)
  • Error handling is minimal at best

PR:s are more than welcome.