Created
December 4, 2012 17:59
-
-
Save jordanlewis/4206895 to your computer and use it in GitHub Desktop.
PFDS Exercise 2.3
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)) | |
| } 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