×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Scala
Posted by: osocron coder
Added: Sep 13, 2016 10:15 PM
Views: 7
Polish notation
  1. val ops = "+-/*"
  2.  
  3.   def evalOp(s: String, n: String, m: String): String = s match {
  4.     case "+" => (n.toInt + m.toInt).toString
  5.     case "-" => (m.toInt - n.toInt).toString
  6.     case "*" => (n.toInt * m.toInt).toString
  7.     case "/" => (m.toInt / n.toInt).toString
  8.   }
  9.  
  10.   def evalReversePolishNotation(input: List[String]): Double = input.foldLeft(List[String]())((acc, s) => {
  11.     if (ops.contains(s)) evalOp(s, acc.head, acc.tail.head) :: acc.drop(2) else s :: acc
  12.   }).head.toInt