Last active
December 19, 2015 22:28
-
-
Save mitsuse/6027133 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.util.parsing.combinator._ | |
class Tree[L](val label: L, val children: Seq[Tree[L]]) extends Traversable[Tree[L]] { | |
val numOfChildren = children.length | |
def this(label: L) = this(label, Seq[Tree[L]]()) | |
override def toString: String = { | |
if (isTerminal) { | |
return label.toString | |
} else { | |
return "(" + label.toString + " " + children.mkString(" ") + ")" | |
} | |
} | |
def foreach[U](f: Tree[L] => U): Unit = { | |
f(this) | |
children.foreach(_.foreach(f)) | |
} | |
def terminals: Seq[L] = { | |
this.withFilter(_.isTerminal).map(_.label).toSeq | |
} | |
def isTerminal: Boolean = children.isEmpty | |
def isBinary: Boolean = numOfChildren == 2 | |
def isUnary: Boolean = numOfChildren == 1 | |
def isPreTerminal: Boolean = isUnary && children(0).isTerminal | |
} | |
object Tree extends RegexParsers { | |
private def labelParser = "[^ ()]+".r | |
private def terminalParser: Parser[Tree[String]] = labelParser ^^ { | |
result => { new Tree(result) } | |
} | |
private def posParser = "(" ~> labelParser ~ terminalParser <~ ")" ^^ { | |
result => { new Tree(result._1, Seq(result._2)) } | |
} | |
private def consParser: Parser[Tree[String]] = | |
"(" ~> labelParser ~ rep(consParser | posParser) <~ ")" ^^ { | |
result => { new Tree(result._1, result._2) } | |
} | |
def fromString(expr: String): ParseResult[Tree[String]] = parseAll(consParser, expr) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment