Last active
August 29, 2015 14:01
-
-
Save gtopper/f4e16d15b8043baa6d00 to your computer and use it in GitHub Desktop.
Functional solution for ReversePolishNotation
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
object ReversePolishNotation { | |
type Operand = Double | |
type BinaryOp = (Operand, Operand) => Operand | |
val parseOp: String => Double = _.toDouble | |
val opMap: Map[String, BinaryOp] = Map( | |
"+" -> (_ + _), | |
"-" -> (_ - _), | |
"*" -> (_ * _), | |
"/" -> (_ / _) | |
) | |
val parseElem: String => Any = s => opMap.getOrElse(s, parseOp(s)) | |
val parse: String => Seq[Any] = _.split(" ").map(parseElem).toList | |
val eval: Seq[Any] => Double = { | |
case (x: Operand) :: Nil => x | |
case (o1: Operand) :: (o2: Operand) :: (op: BinaryOp) :: xs => eval(op(o1, o2) +: xs) | |
} | |
def eval(s: String): Double = eval(parse(s)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment