Created
March 10, 2019 09:33
-
-
Save jmcd/8764e7f06f35b8890a2ca8b9b02fe858 to your computer and use it in GitHub Desktop.
RPN in scala
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
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