Skip to content

Instantly share code, notes, and snippets.

@andrelaszlo
Forked from AlexanderWingard/PitTree.scala
Created October 28, 2009 22:41
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 andrelaszlo/220931 to your computer and use it in GitHub Desktop.
Save andrelaszlo/220931 to your computer and use it in GitHub Desktop.
Added the new pretty toString method
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 = ".\n"+toString(children.toList, "", "")
def toString(children: List[(String, PitTree[T])], prefix: String, name: String): String = {
def formatValue(o: Option[T]): String = o match {
case Some(s) => "= " + s.toString
case None => ""
}
children match {
case Nil => ""
case h::Nil => // last element
val (name, subTree) = h
prefix + "`-- " + name + " " + formatValue(subTree.value) + "\n" +
toString(subTree.children.toList, prefix + " ", name)
case h::t =>
val (name, subTree) = h
prefix + "|-- " + name + " " + formatValue(subTree.value) + "\n" +
toString(subTree.children.toList, prefix + "| ", name) +
toString(t, prefix, name)
}
}
}
object PitTree {
def apply[T]() = new PitTree[T]()
def apply[T](value : T) = new PitTree[T](value)
}
object Test extends Application {
var pitTree = PitTree[Int]()
pitTree = pitTree("/apa") = 10
pitTree = pitTree("/apa") = 20
pitTree = pitTree("gris/kossa/häst") = 30
pitTree = pitTree("gris/kossa/apa") = 10
pitTree = pitTree("gris/kossa/katt/firre") = 4
pitTree = pitTree("flodhaest") = 2
println(pitTree)
//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