質問

How do I replace the first element in a sorted set in Scala? Is there an analogous function to 'patch' for Sorted Sets? Is it even possible?

val a = SortedSet(1,5,6)
val b = a.patch(0, seq[2], 1)
println(b)

Result should be:

TreeSet(2, 5, 6)
役に立ちましたか?

解決

How about this:

scala> val a = SortedSet(1,5,6)
a: scala.collection.SortedSet[Int] = TreeSet(1, 5, 6)


scala> val b = a.drop(1) + 2
b: scala.collection.SortedSet[Int] = TreeSet(2, 5, 6)

Note: You're not really replacing anything here (at least not like an array.) What you are doing is taking a SortedSet and using drop to remove the first element (which happens to be the lowest value in sorted order in this case) and then you are adding another element to the set. 2 is only in the first position because that is where it is supposed to be in sorted order.

scala> a.drop(1) + 10
res21: scala.collection.SortedSet[Int] = TreeSet(5, 6, 10)

As you see, if you add 10, it also takes its place in sorted order which is at the end.

Furthermore, because sets cannot contain duplicates, doing something like:

scala> a.drop(1) + 6
res22: scala.collection.SortedSet[Int] = TreeSet(5, 6)

removes the first element and leaves you with only two elements in the set. This is because 6 was already in the set, so it is not added (again, a property of a set is that it does not contain duplicates.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top