Advertisement
Guest User

Untitled

a guest
Aug 1st, 2014
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.03 KB | None | 0 0
  1. class ReversePolishCalculator extends JavaTokenParsers with Maths {
  2.   def expr:   Parser[Float] = rep(term ~ operator) ^^ {
  3.     case terms =>
  4.       var stack  = List.empty[Float]
  5.       var lastOp: (Float, Float) => Float = add
  6.       terms.foreach(t =>
  7.         t match {
  8.           case nums ~ op => lastOp = op; stack = reduce(stack ++ nums, op)
  9.         }
  10.       )
  11.       stack.reduceRight((x, y) => lastOp(y, x))
  12.   }
  13.   def term: Parser[List[Float]] = rep(factor)
  14.   def factor: Parser[Float] = num | "(" ~> expr <~ ")" ^^ (_.toFloat)
  15.   def num: Parser[Float] = floatingPointNumber ^^ (_.toFloat)
  16.   def operator: Parser[(Float, Float) => Float] = ("*" | "/" | "+" | "-") ^^ {
  17.     case "+" => add
  18.     case "-" => sub
  19.     case "*" => mul
  20.     case "/" => div
  21.   }
  22.   def reduce(nums: List[Float], op: (Float, Float) => Float): List[Float] = {
  23.     val result = nums.reverse match {
  24.       case x :: y :: xs => xs ++ List(op(y, x))
  25.       case List(x)      => List(x)
  26.       case _            => List.empty[Float]
  27.     }
  28.     result
  29.   }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement