Skip to content

Instantly share code, notes, and snippets.

Created December 10, 2014 20:03
Show Gist options
  • Save anonymous/b722da9d8c69d83509b4 to your computer and use it in GitHub Desktop.
Save anonymous/b722da9d8c69d83509b4 to your computer and use it in GitHub Desktop.
package com.twitter.univ.calculator
object Operator {
val all: Map[String, (Int, Int) => Int] =
Map("+" -> (_ + _),
"-" -> (_ - _),
"*" -> (_ * _),
"/" -> (_ / _))
def unapply(str: String) = all.get(str)
}
object FunctionalCalcApp extends App {
val result =
args.foldLeft(Nil: List[Int]) {
case (_2 :: _1 :: tail, Operator(op)) => op(_1, _2) :: tail
case (_, Operator(op)) => throw new IllegalArgumentException // not enough operands
case (opStack, num) => num.toInt :: opStack // NumberFormatException for invalid input
}
println(result.head) // not enough operators if result.length > 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment