以防万一有人需要。
scala BST 容器的实现。
trait BSTree[+A]
case object Empty extends BSTree[Nothing]
case class Node[+A](left: BSTree[A], x: A, right: BSTree[A]) extends BSTree[A]
object BSTree {
def insert[T](t: BSTree[T], k: T)(
implicit ord: T => Ordered[T]
): BSTree[T] = t match {
case Empty => Node(Empty, k, Empty)
case Node(l, x, r) if k < x => Node(insert(l, k), x, r)
case Node(l, x, r) if k == x => Node(l, k, r)
case Node(l, x, r) => Node(l, x, insert(r, k))
}
def toList[T](t: BSTree[T]): List[T] = t match {
case Empty => Nil
// preorder traverse
case Node(l, x, r) => x :: toList(l) ++ toList(r)
}
def apply[T](as: T*)(implicit ord: T => Ordered[T]): BSTree[T] = as.foldLeft(
Empty: BSTree[T])((t, e) => insert(t, e))
}
object Main extends App {
case class WordCount(c: Char, var count: Int) {
override def toString: String = s"'$c' -> $count"
}
implicit def wordCountConvert(x: WordCount): Ordered[WordCount] =
(that: WordCount) => if (x.c.<(that.c)) -1
else if (x.c == that.c) {
that.count = x.count + 1
0
} else 1
val content = "Scala Cool!"
val wordCountTree = BSTree(content.filter(_.isLetter).map(WordCount(_, 1)): _*)
println(BSTree.toList(wordCountTree))
}
并在此处输出
List('S' -> 1, 'C' -> 1, 'c' -> 1, 'a' -> 2, 'a' -> 1, 'l' -> 2, 'o' -> 2, 'l' -> 1, 'o' -> 1)
参见示例here