Created
October 22, 2014 20:55
-
-
Save hhimanshu/12c8c86157042b3a9369 to your computer and use it in GitHub Desktop.
Scala Calculator
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 | |
object Calculator { | |
def main(args: Array[String]): Unit = | |
if (args.length != 1) { | |
throw new IllegalArgumentException("usage: Calculator <expression>") | |
} else { | |
val expression = args(0) | |
val tokens = expression.split(" ") | |
val stack = new mutable.Stack[Int] | |
for (token <- tokens) { | |
token match { | |
case "+" => | |
val rhs = stack.pop() | |
val lhs = stack.pop() | |
stack.push(lhs + rhs) | |
case "-" => | |
val rhs = stack.pop() | |
val lhs = stack.pop() | |
stack.push(lhs - rhs) | |
case "*" => | |
val rhs = stack.pop() | |
val lhs = stack.pop() | |
stack.push(lhs * rhs) | |
case "/" => | |
val rhs = stack.pop() | |
val lhs = stack.pop() | |
stack.push(lhs / rhs) | |
case _ => try { | |
stack.push(token.toInt) | |
} catch { | |
case _ => throw new IllegalArgumentException("invalid token " + token) | |
} | |
} | |
} | |
println(stack.pop()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment