Created
December 10, 2014 20:03
-
-
Save anonymous/b722da9d8c69d83509b4 to your computer and use it in GitHub Desktop.
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
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