在Scala中按名称编译和运行函数?

时间:2013-09-09 07:23:42

标签: scala classpath scala-2.10 scala-2.9 scalac

继续阅读硕士论文[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, “Combinator Parsing in 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

2 个答案:

答案 0 :(得分:0)

您的代码没有任何问题 - 您是否在运行之前使用scalac进行编译?

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

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

 # Assuming the current directory contains only one scala source file with a 
 # main method:
 sbt 'run "10.5 - 4*2"'

答案 1 :(得分: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))))))

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