Created
February 21, 2017 16:05
-
-
Save speedcom/c175564c007650506c6240c47e515b57 to your computer and use it in GitHub Desktop.
Exemplary ONP implementation in Scala
This file contains 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
import scala.collection.mutable.Stack | |
val equation = "12 2 3 4 * 10 5 / + * +" | |
val ops = equation.split(" ") | |
val stack = new Stack[Int]() | |
def *(a: Int, b: Int) = a * b | |
def /(a: Int, b: Int) = a / b | |
def +(a: Int, b: Int) = a + b | |
val operators: Set[String] = Set("*", "/", "+") | |
def toOp: PartialFunction[String, (Int, Int) => Int] = { | |
case "*" => * | |
case "/" => / | |
case "+" => + | |
} | |
ops.foreach { i => | |
if(operators.contains(i)) { | |
val a = stack.pop() | |
val b = stack.pop() | |
val result = toOp(i)(b, a) | |
stack.push(result) | |
} else { | |
stack.push(i.toInt) | |
} | |
} | |
println("result: " + stack.head) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment