import scala.util.parsing.combinator.JavaTokenParsers object ParserCombinator extends JavaTokenParsers { def main(args:Array[String]){ val multiply:Parser[Double] = floatingPointNumber ~ rep( ("*" | "/") ~ floatingPointNumber ^^ { case "*" ~ (factor:String) => left:Double => left * factor.toDouble case "/" ~ (factor:String) => left:Double => left / factor.toDouble } ) ^^ { case (seed:String) ~ (fnList:List[Double=>Double]) => fnList.foldLeft(seed.toDouble)((left, fn) => fn(left)) } val result = this.parseAll(multiply, "2*4/8*5") if(result.successful){ println(result.get) } } }
时间: 2024-10-10 07:00:39