Skip to content

Instantly share code, notes, and snippets.

@7shi
Forked from shigemk2/17-225401.scala
Created July 18, 2015 02:47
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 7shi/eb952e5687ab1cb4f1c9 to your computer and use it in GitHub Desktop.
Save 7shi/eb952e5687ab1cb4f1c9 to your computer and use it in GitHub Desktop.
def rpn(str: String): Int = rpnPrime(str.split(' ').toList, Nil)
def rpnPrime(str: List[String], stack: List[Int]): Int = (str, stack) match {
case ("+"::t, y::x::zs) => rpnPrime(t, (x + y) :: zs)
case ("-"::t, y::x::zs) => rpnPrime(t, (x - y) :: zs)
case ("*"::t, y::x::zs) => rpnPrime(t, (x * y) :: zs)
case ("/"::t, y::x::zs) => rpnPrime(t, (x / y) :: zs)
case ("%"::t, y::x::zs) => rpnPrime(t, (x % y) :: zs)
case ( n::t, zs) => rpnPrime(t, (n.toInt) :: zs)
case _ => stack.head
}
println(rpn("1 3 +"))
println(rpn("1 3 + 5 2 - *"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment