Skip to content

Instantly share code, notes, and snippets.

@speedcom
Created February 21, 2017 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save speedcom/c175564c007650506c6240c47e515b57 to your computer and use it in GitHub Desktop.
Save speedcom/c175564c007650506c6240c47e515b57 to your computer and use it in GitHub Desktop.
Exemplary ONP implementation in Scala
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