alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Scala example source code file (ListParser.scala)

This example Scala source code file (ListParser.scala) is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Java - Scala tags/keywords

array, char, id, int, int, list, lst, lst, num, num, parsers, string, tree, tree

The Scala ListParser.scala source code

package examples.parsing

import scala.util.parsing.combinator.{Parsers, ImplicitConversions, ~, mkTilde}
import scala.util.parsing.input.CharArrayReader

object listParser {
  abstract class Tree
  case class Id(s: String)          extends Tree
  case class Num(n: Int)            extends Tree
  case class Lst(elems: List[Tree]) extends Tree

  import Character.{isLetter, isLetterOrDigit, isDigit}
  def mkString(cs: List[Any]) = cs.mkString("")

  class ListParsers extends Parsers {
    type Elem = Char
    
    lazy val ident = rep1(elem("letter", isLetter), elem("letter or digit", isLetterOrDigit)) ^^ {cs => Id(mkString(cs))}
    lazy val number = chainl1(elem("digit", isDigit) ^^ (_ - '0'), success{(accum: Int, d: Int) => accum * 10 + d}) ^^ Num
    lazy val list = '(' ~> repsep(expr, ',') <~ ')' ^^ Lst
    lazy val expr: Parser[Tree] = list | ident | number
  }

  def main(args: Array[String]) {
    println(
      if (args.length == 1) {
        (new ListParsers).expr(new CharArrayReader(args(0).toCharArray()))
      }
      else
        "usage: scala examples.parsing.listParser <list-string>"
    )
  }
}

Other Scala examples (source code examples)

Here is a short list of links related to this Scala ListParser.scala source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.