Skip to content

Instantly share code, notes, and snippets.

@jmcd
Created March 10, 2019 09:33
Show Gist options
  • Save jmcd/8764e7f06f35b8890a2ca8b9b02fe858 to your computer and use it in GitHub Desktop.
Save jmcd/8764e7f06f35b8890a2ca8b9b02fe858 to your computer and use it in GitHub Desktop.
RPN in scala
import scala.collection.mutable.ListBuffer
object Main extends App {
def getOperator(s: String): Option[((Int, Int) => Int)] = {
s match {
case "+" => Some(_+_)
case "-" => Some(_-_)
case "/" => Some(_/_)
case "*" => Some(_*_)
case _ => None
}
}
val finalStack = args.foldLeft(List[Int]()) { (stack, token) =>
val mutableStack = stack.to[ListBuffer]
val i = getOperator(token) match {
case Some(operator) =>
val rhs = mutableStack.remove(0)
val lhs = mutableStack.remove(0)
operator.apply(lhs, rhs)
case None => token.toInt
}
mutableStack.insert(0, i)
mutableStack.toList
}
print(finalStack(0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment