Scala immutable SortedSets are not “stable” when removed

I need to have a fixed object in scala 2.7.5, and one of its members is immutable Sort . I have no problem adding to synthesize, it gives:

class MyClass[A](s:SortedSet[A]) {
  ...
  def  + (elem:A):MyClass[A] {
    new MyClass(s + elem)
  }
}

And it works, since the + operator is an overload in the sortedSet to return a SortedSet.

Unfortunately, the deletion of the item is in error because - methos is not overloaded:

class MyClass[A](s:SortedSet[A]) {
  ...
  def  - (elem:A):MyClass[A] {
    new MyClass(s - elem) // Compiler error: (s - elem) is a Set[A]
  }
}

Does anyone know how I can get a sorted set when I suppress an element, knowing that: - I do not want to use a more specific type of set, like TreeSet. - I cannot use a less specific attribute like Set [A] instead of my SortedSet.

+3
3

2.8, , .

SortedSetLike.scala (- SortedSet)

trait SortedSetLike[A, +This <: SortedSet[A] with SortedSetLike[A, This]] extends Sorted[A, This] with SetLike[A, This]

This a SortedSet. SetLike.scala -

def - (elem: A): This

, SortedSet SortedSet.

+3

, , - SortedSet. . Set - , , , SortedSet , .

, . , asInstanceOf 2.8.: -)

class MyClass[A](s: SortedSet[A]) {
  def -(elem: A)(implicit view: A => Ordered[A]): MyClass[A] = {
    new MyClass(TreeSet(s.toList - elem: _*))
  }
}
+1

I think all you have to do is drop it. "-" returns Set, but is also a SortedSet. It may not be very pretty, but it works:

class MyClass[A](s:SortedSet[A]) {
    def  +(elem:A): MyClass[A] = {
      new MyClass(s + elem)
    }

    def  -(elem:A): MyClass[A] = {
      new MyClass((s - elem).asInstanceOf[SortedSet[A]])
    }

    override def toString = "sorted set = " + s
  }

  val a = new MyClass(new TreeSet[Int])
  println(a) // prints "sorted set = Set()"
  val b = a + 1
  println(b) // prints "sorted set = Set(1)"
  val c = a - 1
  println(c) // prints "sorted set = Set()"
0
source

Source: https://habr.com/ru/post/1715062/


All Articles