Skip to content

Instantly share code, notes, and snippets.

@jianzwang
Created April 9, 2012 14:38
Show Gist options
  • Select an option

  • Save jianzwang/2343893 to your computer and use it in GitHub Desktop.

Select an option

Save jianzwang/2343893 to your computer and use it in GitHub Desktop.
Scala Calculator
/**
* This class is used to parse a String and calculate the value of the expression
* assertEquals( 34,ExprParser.parse("1+2+3+4*3+4",(x:Double)=>x+1))
*/
import scala.util.parsing.combinator._
object ExprParser extends JavaTokenParsers {
/*
* text is the input String,func is a function effect on every element
*/
def parse(text: String, func: Double => Double ) = {
def expr = term ~ rep("+" ~ term | "-" ~ term) ^^ {
case v ~ f => f.foldLeft(v) {
case (x, "+" ~ term) => x + term
case (x, "-" ~ term) => x - term
}
}
def term = factor ~ rep("*" ~ factor | "/" ~ factor) ^^ {
case v ~ f => f.foldLeft(v) {
case (x, "*" ~ term) => x * term
case (x, "/" ~ term) => x / term
}
}
def factor: Parser[Double] =
(floatingPointNumber ^^ { case x => {
func(x.toString.toDouble)
}}) | "(" ~> expr <~ ")"
parseAll(expr, text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment