Skip to content

Instantly share code, notes, and snippets.

@tbrown1979
Created September 4, 2013 17:30
Show Gist options
  • Save tbrown1979/6440126 to your computer and use it in GitHub Desktop.
Save tbrown1979/6440126 to your computer and use it in GitHub Desktop.
IntSet from Functional Programming Coursera. Help me understand the union function!
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