Created
November 14, 2018 06:14
-
-
Save mizhi/3d9120028d95d50cb7d0cff72bc816c6 to your computer and use it in GitHub Desktop.
A terser implementation.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //*=== Tuesday Nov 13th 2018 - Daily Programmer ===* | |
| // | |
| //*[RPN Calculator]* | |
| // | |
| //"RPN" stands for "Reverse Polish Notation". In an RPN world, instead of using normal "infix" notation, e.g. `2 + 2`, you use "postfix" notation, e.g. `2 2 +` | |
| //```1 2 + 3 * => (1 + 2) * 3 => 9 | |
| //1 2 3 * + => 1 + (2 * 3) => 7``` | |
| // | |
| //Write an RPN calculator with the following methods: | |
| // ```calculator.push() // Adds the element to the stack | |
| //calculator.plus() // Adds the elements in the stack | |
| //calculator.minus() // Adds the elements in the stack | |
| //calculator.multiply() // Adds the elements in the stack | |
| //calculator.divide() // Adds the elements in the stack | |
| object RPN { | |
| def apply(equation: String): Int = { | |
| this(equation.split(" "): _*) | |
| } | |
| def apply(equationParts: String*): Int = { | |
| equationParts.foldLeft(List.empty[Int])( | |
| (results, opOrOperand) => { | |
| binOps.get(opOrOperand) match { | |
| case Some(func) => func(results.tail.head, results.head) :: results.tail.tail | |
| case None => opOrOperand.toInt :: results | |
| } | |
| } | |
| ).head | |
| } | |
| val binOps = Map( | |
| "+" -> ((x: Int, y: Int) => x + y), | |
| "-" -> ((x: Int, y: Int) => x - y), | |
| "*" -> ((x: Int, y: Int) => x * y), | |
| "/" -> ((x: Int, y: Int) => x / y) | |
| ) | |
| } | |
| RPN("2", "3", "+") | |
| RPN(List("2", "3", "+"): _*) | |
| RPN("2 3 + 2 *") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment