Skip to content

Instantly share code, notes, and snippets.

@AlexanderWingard
Created October 28, 2009 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlexanderWingard/220928 to your computer and use it in GitHub Desktop.
Save AlexanderWingard/220928 to your computer and use it in GitHub Desktop.
class PitTree[T](val children : Map[String, PitTree[T]], val value : Option[T]) extends Map[String, T] {
def this() = this(Map(), None)
def this(value : T) = this(Map(), Some(value))
def update(path : String, upVal : T) : PitTree[T] = update(splitPath(path), upVal)
def update(path : List[String], upVal : T) : PitTree[T] = path match {
case Nil =>
new PitTree[T](upVal)
case h :: t =>
val child = children.getOrElse(h, new PitTree[T]()).update(t, upVal)
new PitTree[T](children + (h -> child), value)
}
def get(path : String) : Option[T] = get(splitPath(path))
def get(path : List[String]) : Option[T] = path match {
case Nil =>
value
case h :: t =>
if(children.keysIterator.exists(_ == h))
children(h).get(t)
else
None
}
def + [T1 >: T](kv: (String, T1)): PitTree[T] = this // TODO: Implement me
def - (key: String): PitTree[T] = this // TODO: Implement me
def iterator = Iterator() // TODO: Implement me
def splitPath(path : String) = path.split('/').filter(_ != "").toList
override def toString = {
def formatTree(children : Map[String, PitTree[T]], prefix : String) : String = {
children.toList.take(children.size).map((pair) => {
val (path, tree) = pair
val valueString = if (tree.value.isDefined) " = " + tree.value.get.toString else " "
prefix + path + valueString + "\n" + formatTree(tree.children, prefix + "|`")
}
).mkString}
formatTree(children, "")
}
}
object PitTree {
def apply[T]() = new PitTree[T]()
def apply[T](value : T) = new PitTree[T](value)
}
object Test {
def main(args: Array[String]) {
//TODO: Add example with comments showing results of operations.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment