Advertisement
jules0707

IntSets

Feb 27th, 2017
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.33 KB | None | 0 0
  1. import java.util.Collections.EmptySet
  2.  
  3. object week3 {
  4.  
  5.   val t1 = new NonEmpty(3, Empty, Empty)          //> t1  : NonEmpty = {.3.}
  6.   val t2 = t1 incl 4                              //> t2  : IntSet = {.3{.4.}}
  7.   t1 union Empty                                  //> res0: IntSet = {.3.}
  8.   val t5 = new NonEmpty(5, new NonEmpty(3, new NonEmpty(2, Empty, Empty), Empty), new NonEmpty(7, Empty, Empty))
  9.                                                   //> t5  : NonEmpty = {{{.2.}3.}5{.7.}}
  10. }
  11.  
  12. abstract class IntSet {
  13.   def incl(x: Int): IntSet
  14.   def contains(x: Int): Boolean
  15.   def union(other: IntSet): IntSet
  16. }
  17.  
  18. object Empty extends IntSet {
  19.   def contains(x: Int): Boolean = false
  20.   def incl(x: Int): IntSet = new NonEmpty(x, Empty, Empty)
  21.   def union(other: IntSet): IntSet = other
  22.   override def toString = "."
  23. }
  24.  
  25. class NonEmpty(elem: Int, left: IntSet, right: IntSet) extends IntSet {
  26.   def union(other: IntSet): IntSet =
  27.     ((left union right) union other) incl elem
  28.  
  29.   def contains(x: Int): Boolean =
  30.     if (x < elem) left contains x
  31.     else if (x > elem) right contains x
  32.     else true
  33.  
  34.   def incl(x: Int): IntSet =
  35.     if (x < elem) new NonEmpty(elem, left incl x, right)
  36.     else if (x > elem) new NonEmpty(elem, left, right incl x)
  37.     else this
  38.  
  39.   override def toString = "{" + left + elem + right + "}"
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement