Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ReversePolishCalculator extends JavaTokenParsers with Maths {
- def expr: Parser[Float] = rep(term ~ operator) ^^ {
- case terms =>
- var stack = List.empty[Float]
- var lastOp: (Float, Float) => Float = add
- terms.foreach(t =>
- t match {
- case nums ~ op => lastOp = op; stack = reduce(stack ++ nums, op)
- }
- )
- stack.reduceRight((x, y) => lastOp(y, x))
- }
- def term: Parser[List[Float]] = rep(factor)
- def factor: Parser[Float] = num | "(" ~> expr <~ ")" ^^ (_.toFloat)
- def num: Parser[Float] = floatingPointNumber ^^ (_.toFloat)
- def operator: Parser[(Float, Float) => Float] = ("*" | "/" | "+" | "-") ^^ {
- case "+" => add
- case "-" => sub
- case "*" => mul
- case "/" => div
- }
- def reduce(nums: List[Float], op: (Float, Float) => Float): List[Float] = {
- val result = nums.reverse match {
- case x :: y :: xs => xs ++ List(op(y, x))
- case List(x) => List(x)
- case _ => List.empty[Float]
- }
- result
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement