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
There's nothing wrong with your code - are you actually compiling it with
scalac
before running it?As an aside, if you plan on doing any significant coding in Scala theb
sbt
is highly recommended. You can run the following code insbt
as well: