Compiling and running functions by name in Scala?

301 views Asked by At

Following along in this Masters thesis[1] to learn parsing in Scala, but can't figure out how to get this example working (see pages 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.

Unfortunately I cannot get it to run in either Scala 2.9.3 or 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)

So then trying with the 2.11 scalac and scala:

> scala ArithParserCLI "10.5 - 4*2"
No such file or class on classpath: ArithParserCLI
2

There are 2 answers

1
Faiz On

There's nothing wrong with your code - are you actually compiling it with scalac before running it?

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

As an aside, if you plan on doing any significant coding in Scala theb sbt is highly recommended. You can run the following code in sbt as well:

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

Actually, I've just taken the source code without any change and done the following:

[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 version 2.9.2. So, the error is likely in your local configuration.