Created
September 4, 2013 17:30
-
-
Save tbrown1979/6440126 to your computer and use it in GitHub Desktop.
IntSet from Functional Programming Coursera. Help me understand the union function!
This file contains 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
abstract class IntSet { | |
def incl(x: Int): IntSet | |
def contains(x: Int): Boolean | |
def union(other: IntSet): IntSet | |
} | |
class Empty extends IntSet { | |
def incl(x: Int): IntSet = new NonEmpty(x, new Empty, new Empty) | |
def contains(x: Int): Boolean = false | |
override def toString = "." | |
def union(other: IntSet): IntSet = other | |
} | |
class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet { | |
def incl(x: Int): IntSet = | |
if ( x > elem ) new NonEmpty( elem, left, right incl x ) | |
else if ( x < elem ) new NonEmpty( elem, left incl x, right ) | |
else this | |
def contains( x: Int ): Boolean = | |
if ( x < elem ) left contains x | |
else if ( x > elem ) right contains x | |
else true | |
override def toString = "{" + left + elem + right + "}" | |
def union(other: IntSet): IntSet = | |
((left union right) union other) incl elem | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment