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) } } }
本文出自 “Frank” 博客,请务必保留此出处http://zengfanhong.blog.51cto.com/8894077/1600167
原文地址:http://zengfanhong.blog.51cto.com/8894077/1600167