Search code examples
scalaparser-combinators

How to Install scala parser combinators


So, i'm using Scala 2.13.12 on ubuntu, installed via coursier. Recently i installed via sudo apt-get install the package for parser combinators, but can't import it.

In the official github page, it says to modify a build file, but where can i find it?


Solution

  • It's very common for Scala projects to be built with a tool called sbt, an alternative to other JVM build tools like Maven and Gradle which is written in Scala and uses Scala as a language to define your build.

    As you mentioned, the library itself says to add the dependency to your build.sbt here.

    If you want to follow this approach, you should first install sbt (here are a few options on how to it).

    Once you have that installed, here is a very brief example of how to get started:

    1. In a new directory, create the file build.sbt with the following content

      scalaVersion := "2.13.12"
      
      libraryDependencies ++= Seq(
        "org.scala-lang.modules" %% "scala-parser-combinators" % "2.3.0",
      )
      
    2. In the same directory, create the directory following the standard structure followed by sbt

      mkdir -p src/main/scala
      
    3. Create the file src/main/scala/SimpleParser.scala with the example provided by the library documentation:

      import scala.util.parsing.combinator._
      
      case class WordFreq(word: String, count: Int) {
        override def toString = s"Word <$word> occurs with frequency $count"
      }
      
      class SimpleParser extends RegexParsers {
        def word: Parser[String]   = """[a-z]+""".r       ^^ { _.toString }
        def number: Parser[Int]    = """(0|[1-9]\d*)""".r ^^ { _.toInt }
        def freq: Parser[WordFreq] = word ~ number        ^^ { case wd ~ fr => WordFreq(wd,fr) }
      }
      
      object TestSimpleParser extends SimpleParser {
        def main(args: Array[String]) = {
          parse(freq, "johnny 121") match {
            case Success(matched,_) => println(matched)
            case Failure(msg,_) => println(s"FAILURE: $msg")
            case Error(msg,_) => println(s"ERROR: $msg")
          }
        }
      }
      
    4. run sbt run, at this point you should see Coursier download the library and its dependency, followed by the output of running the command (downloading the dependency will only happen on the first run)