Skip to content

Instantly share code, notes, and snippets.

@kamiyaowl kamiyaowl/Main.scala
Last active Aug 29, 2015

Embed
What would you like to do?
reversepolish calculator(Do not use parsercombinator)
import scala.collection.immutable.Stack
object Main {
def binOp(q:Stack[Double])(f:(Double,Double) => Double) : Stack[Double] = {
val (b,q2) = q.pop2
val (a,q3) = q2.pop2
q3.push(f(a,b))
}
def unaryOp(q:Stack[Double])(f:(Double) => Double) : Stack[Double] = {
val (a,q2) = q.pop2
q2.push(f(a))
}
def calculator(tokens:List[String])(implicit q:Stack[Double] = Stack.empty) : Stack[Double] = tokens.headOption match {
//binary operator
case Some("+") => calculator(tokens.tail)(binOp(q){ _ + _ })
case Some("-") => calculator(tokens.tail)(binOp(q){ _ - _ })
case Some("*") => calculator(tokens.tail)(binOp(q){ _ * _ })
case Some("/") => calculator(tokens.tail)(binOp(q){ _ / _ })
//unary operator
case Some("sqrt") => calculator(tokens.tail)(unaryOp(q){ math.sqrt })
//number push
case Some(str) => calculator(tokens.tail)(q.push(str.toDouble))
//end
case None => q
}
def main(args: Array[String]): Unit = {
val src = "5 5 * 2 + 3 / sqrt"// => 3.0
println(calculator(src.split(" ").toList).pop2._1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.