|
Scala example source code file (ListParser.scala)
The Scala ListParser.scala source codepackage 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 |
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.