Created
April 9, 2012 14:38
-
-
Save jianzwang/2343893 to your computer and use it in GitHub Desktop.
Scala Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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