Skip to content

Instantly share code, notes, and snippets.

@jordanlewis
Created December 4, 2012 17:59
Show Gist options
  • Select an option

  • Save jordanlewis/4206895 to your computer and use it in GitHub Desktop.

Select an option

Save jordanlewis/4206895 to your computer and use it in GitHub Desktop.
PFDS Exercise 2.3
class ElementAlreadyExistsException extends RuntimeException
class UnbalancedTreeSet[T] private (tree: BinaryTree[T]) (implicit val ordering: Ordering[T]) extends Set[T] {
// ...
def insert(x: T) = try {
newSet(UnbalancedTreeSet.insert(x, tree))
} catch {
case _:ElementAlreadyExistsException => this
}
// ...
}
object UnbalancedTreeSet {
// ...
private def insert[T](x: T, t: BinaryTree[T])(implicit ordering: Ordering[T]): BinaryTree[T] = t match {
case BinaryTreeLeaf => BinaryTreeNode(BinaryTreeLeaf, x, BinaryTreeLeaf)
case BinaryTreeNode(a, y, b) =>
if (ordering.lt(x, y)) BinaryTreeNode(insert(x, a), y, b)
else if (ordering.lt(y, x)) BinaryTreeNode(a, y, insert(x, b))
else throw new ElementAlreadyExistsException
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment