Skip to content

Instantly share code, notes, and snippets.

@Rogach
Created January 20, 2012 08:24
Show Gist options
  • Save Rogach/1646123 to your computer and use it in GitHub Desktop.
Save Rogach/1646123 to your computer and use it in GitHub Desktop.
Simple math interpreter
object Interpreter {
def main(args:Array[String]) = {
(new SimpleParser).parseString("2*3.2 + 3*(36.07/4 - 10)").println
}
import scala.util.parsing.combinator._
class SimpleParser extends JavaTokenParsers {
def expr: Parser[Double] = (
term~"+"~expr ^^ { case a~"+"~b => a + b }
| term~"-"~expr ^^ { case a~"-"~b => a - b }
| term)
def term: Parser[Double] = (
num~"*"~term ^^ { case a~"*"~b => a * b}
| num~"/"~term ^^ { case a~"/"~b => a / b}
| num)
def num: Parser[Double] =
floatingPointNumber ^^ (_.toDouble) |
"("~expr~")" ^^ { case "("~a~")" => a }
def parseString = parseAll(expr, (_:String)) match {
case Success(result,_) => "Result: %.4f" format result
case Failure(msg, _) => "Parsing failed: %s" format msg
}
}
} /*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment