0

跟随这篇硕士论文[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
4

2 回答 2

0

您的代码没有任何问题-您实际上是scalac在运行它之前对其进行编译吗?

 scalac ArithParserCLI.scala  # or whatever your source file is named
 scala ArithParserCLI "10.5 - 4*2"

sbt顺便说一句,如果您打算在 Scala 中进行任何重要的编码,强烈建议您使用theb 。您也可以在其中运行以下代码sbt

 # Assuming the current directory contains only one scala source file with a 
 # main method:
 sbt 'run "10.5 - 4*2"'
于 2013-09-09T08:01:10.113 回答
0

实际上,我只是获取了源代码,没有进行任何更改并执行了以下操作:

[root@centos scala]# scalac parser.scala
[root@centos scala]# scala ArithParserCLI "10.5 - 4*2"
Input: 10.5 - 4*2
Output: [1.11] parsed: ((10.5~List())~List((-~(4.0~List((*~2.0))))))

斯卡拉版本 2.9.2。因此,错误可能在您的本地配置中。

于 2013-09-10T10:22:53.957 回答