Skip to content

Instantly share code, notes, and snippets.

@gtopper
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtopper/f4e16d15b8043baa6d00 to your computer and use it in GitHub Desktop.
Save gtopper/f4e16d15b8043baa6d00 to your computer and use it in GitHub Desktop.
Functional solution for ReversePolishNotation
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