Created
July 18, 2015 03:56
-
-
Save shigemk2/53572571b8db4159df68 to your computer and use it in GitHub Desktop.
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
| 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) => { | |
| println(s"str: $str, stack: $stack") | |
| rpnPrime(t, (x + y) :: zs) | |
| } | |
| case ("-"::t, y::x::zs) => { | |
| println(s"str: $str, stack: $stack") | |
| rpnPrime(t, (x - y) :: zs) | |
| } | |
| case ("*"::t, y::x::zs) => { | |
| println(s"str: $str, stack: $stack") | |
| rpnPrime(t, (x * y) :: zs) | |
| } | |
| case ("/"::t, y::x::zs) => { | |
| println(s"str: $str, stack: $stack") | |
| rpnPrime(t, (x / y) :: zs) | |
| } | |
| case ("%"::t, y::x::zs) => { | |
| println(s"str: $str, stack: $stack") | |
| rpnPrime(t, (x % y) :: zs) | |
| } | |
| case ( n::t, zs) => { | |
| println(s"str: $str, stack: $stack") | |
| rpnPrime(t, (n.toInt) :: zs) | |
| } | |
| case _ => { | |
| println(s"str: $str, stack: $stack") | |
| stack.head | |
| } | |
| } | |
| println(rpn("1 3 +")) | |
| println(rpn("1 3 + 5 2 - *")) |
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
| str: List(1, 3, +), stack: List() | |
| str: List(3, +), stack: List(1) | |
| str: List(+), stack: List(3, 1) | |
| str: List(), stack: List(4) | |
| 4 | |
| str: List(1, 3, +, 5, 2, -, *), stack: List() | |
| str: List(3, +, 5, 2, -, *), stack: List(1) | |
| str: List(+, 5, 2, -, *), stack: List(3, 1) | |
| str: List(5, 2, -, *), stack: List(4) | |
| str: List(2, -, *), stack: List(5, 4) | |
| str: List(-, *), stack: List(2, 5, 4) | |
| str: List(*), stack: List(3, 4) | |
| str: List(), stack: List(12) | |
| 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment