Skip to content

Instantly share code, notes, and snippets.

Created July 9, 2012 06:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3074485 to your computer and use it in GitHub Desktop.
Save anonymous/3074485 to your computer and use it in GitHub Desktop.
プログラミング言語 Scala 8冊目スレ >174
/*
プログラミング言語 Scala 8冊目
From: [174] デフォルトの名無しさん <sage>
Date: 2012/07/09(月) 01:52:58.20
パーサコンビネータの使い方が何度読んでも分からんとです。
int hoge, hage[3] = { 1, 2, 3 }, huge = 5;
をパースする例とか、どっかないですか?
*/
case class IntDef(name: String, value: Int)
case class IntArrayDef(name: String, value: IndexedSeq[Int])
object HogeParser extends scala.util.parsing.combinator.JavaTokenParsers {
lazy val parse = "int" ~> repsep((defIntArray | defInt), ",") <~ ";"
lazy val defInt = ident ~ ("=" ~> wholeNumber).? ^^ {
case ident ~ None => IntDef(ident, 0)
case ident ~ Some(default) => IntDef(ident, default.toInt)
}
lazy val defIntArray = ident ~ "[" ~ wholeNumber ~ "]" ~ ("=" ~ "{" ~> repsep(wholeNumber, ",") <~ "}").? ^^ {
case ident ~ _ ~ size ~ _ ~ None =>
IntArrayDef(ident, IndexedSeq.fill(size.toInt)(0))
case ident ~ _ ~ size ~ _ ~ Some(defaults) =>
IntArrayDef(ident, defaults.map(_.toInt).toIndexedSeq)
}
def apply(str: String) = parseAll(parse, str)
}
/*
scala> HogeParser("int hoge, hage[3] = { 1, 2, 3 }, huge = 5;").get
res0: List[Product with Serializable] = List(IntDef(hoge,0), IntArrayDef(hage,Vector(1, 2, 3)), IntDef(huge,5))
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment