読者です 読者をやめる 読者になる 読者になる

600000007

プログラムと折り紙のブログです。

Scala by Example‎ > 演習6.0.2解答案

Scala by Example > 演習6.0.2の解答案です。

  trait IntSet {
    def incl(x: Int): IntSet
    def contains(x: Int): Boolean
    def union(set: IntSet): IntSet
    def intersection(set: IntSet): IntSet
    def excl(x: Int): IntSet
    def isEmpty: Boolean
  }

  class EmptySet extends IntSet {
    def contains(x: Int): Boolean = false
    def incl(x: Int): IntSet = new NonEmptySet(x, new EmptySet, new EmptySet)
    def union(set: IntSet): IntSet = set
    def intersection(set: IntSet): IntSet = new EmptySet
    def excl(x: Int) = this
    def isEmpty = true
  }

  class NonEmptySet(elem: Int, left: IntSet, right: IntSet) extends IntSet {
    val e: Int = elem
    val l: IntSet = left
    val r: IntSet = right
    def contains(x: Int): Boolean =
      if (x < elem) left contains x
      else if (x > elem) right contains x
      else true
    def incl(x: Int): IntSet =
      if (x < elem) new NonEmptySet(elem, left incl x, right)
      else if (x > elem) new NonEmptySet(elem, left, right incl x)
      else this
    def union(set: IntSet): IntSet = {
      def iter(set: IntSet, result: IntSet): IntSet = {
        set match {
          case n: NonEmptySet =>
            iter(n.r, iter(n.l, result incl n.e))
          case _ => result
        }
      }
      iter(set, this)
    }
    def intersection(set: IntSet): IntSet = {
      def iter(set: IntSet, result: IntSet): IntSet = {
        set match {
          case n: NonEmptySet =>
            iter(n.r, iter(n.l, if (this contains n.e) result incl n.e else result))
          case _ => result
        }
      }
      iter(set, new EmptySet)
    }
    def excl(x: Int): IntSet = {
      def iter(set: IntSet, result: IntSet): IntSet = {
        set match {
          case n: NonEmptySet => iter(n.r, iter(n.l, if (n.e == x) result else result incl n.e))
          case _ => result
        }
      }
      if (this contains x)
        iter(this, new EmptySet)
      else
        this
    }
    def isEmpty = false
  }

case使ったせいでisEmptyが不要に…