Skip to content

Instantly share code, notes, and snippets.

@hhimanshu
Created October 22, 2014 20:55
Show Gist options
  • Save hhimanshu/12c8c86157042b3a9369 to your computer and use it in GitHub Desktop.
Save hhimanshu/12c8c86157042b3a9369 to your computer and use it in GitHub Desktop.
Scala Calculator
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