Created
December 4, 2012 19:18
-
-
Save jordanlewis/4207683 to your computer and use it in GitHub Desktop.
PFDS Exercise 2.4
This file contains hidden or 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
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, None)) | |
} catch { | |
case _:ElementAlreadyExistsException => this | |
} | |
// ... | |
} | |
object UnbalancedTreeSet { | |
// ... | |
private def insert[T](x: T, t: BinaryTree[T], c: Option[T])(implicit ordering: Ordering[T]): BinaryTree[T] = | |
(t, c) match { | |
case (BinaryTreeLeaf, None) => BinaryTreeNode(BinaryTreeLeaf, x, BinaryTreeLeaf) | |
case (BinaryTreeLeaf, Some(d)) => | |
if (ordering.equiv(x, d)) throw new ElementAlreadyExistsException | |
else BinaryTreeNode(BinaryTreeLeaf, x, BinaryTreeLeaf) | |
case (BinaryTreeNode(a, y, b), _) => | |
if (ordering.lt(x, y)) BinaryTreeNode(insert(x, a, c), y, b) | |
else BinaryTreeNode(a, y, insert(x, b, Some(y))) | |
} | |
// ... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment