跟随这篇硕士论文[1]
学习 Scala 中的解析,但不知道如何让这个例子工作(见第 28-29 页):
import util.parsing.combinator.JavaTokenParsers
trait ArithParser extends JavaTokenParsers {
def expr: Parser[Any] = term ~ rep("+" ~ term | "-" ~ term)
def term = factor ~ rep("*" ~ factor | "/" ~ factor)
def factor = floatingPointNumber ^^ {_.toDouble} | "(" ~> expr <~ ")"
}
object ArithParserCLI extends ArithParser {
def main(args: Array[String]) {
for (arg <- args) {
println("Input: " + arg)
println("Output: " + parseAll(expr, arg))
}
}
}
[1]
E. Labun,“Scala 中的组合器解析”,Technische Hochschule Mittelhessen,2012 年。
不幸的是,我无法让它在 Scala 2.9.3 或 Scala 2.11.0-M4 中运行:
> scala29 ArithParserCLI "10.5 - 4*2"
Exception in thread "main" java.lang.RuntimeException: Cannot figure out how to
run target: ArithParserCLI
at scala.sys.package$.error(package.scala:27)
at scala.tools.nsc.GenericRunnerCommand.scala$tools$nsc$GenericRunnerCommand$$guessHowToRun(GenericRunnerCommand.scala:38)
at scala.tools.nsc.GenericRunnerCommand$$anonfun$2.apply(GenericRunnerCommand.scala:48)
at scala.tools.nsc.GenericRunnerCommand$$anonfun$2.apply(GenericRunnerCommand.scala:48)
at scala.Option.getOrElse(Option.scala:108)
at scala.tools.nsc.GenericRunnerCommand.<init>(GenericRunnerCommand.scala:48)
at scala.tools.nsc.GenericRunnerCommand.<init>(GenericRunnerCommand.scala:17)
at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:33)
at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:89)
at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
然后尝试使用 2.11 scalac 和 scala:
> scala ArithParserCLI "10.5 - 4*2"
No such file or class on classpath: ArithParserCLI