This repository has been archived by the owner on Dec 22, 2021. It is now read-only.
/
SortedMultiSet.scala
71 lines (56 loc) · 2.28 KB
/
SortedMultiSet.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package strawman
package collection
package immutable
import strawman.collection.decorators.ImmutableMapDecorator
import strawman.collection.mutable.{Builder, ImmutableBuilder}
/**
* An immutable multiset whose elements are sorted.
* @tparam A Type of elements
*/
class SortedMultiSet[A] private (elems: SortedMap[A, Int])(implicit val ordering: Ordering[A])
extends collection.SortedMultiSet[A]
with Iterable[A]
with collection.SortedMultiSetOps[A, SortedMultiSet, SortedMultiSet[A]]
with collection.IterableOps[A, MultiSet, SortedMultiSet[A]] {
def occurrences: SortedMap[A, Int] = elems
override def iterableFactory: IterableFactory[MultiSet] = MultiSet
override def sortedIterableFactory: SortedIterableFactory[SortedMultiSet] = SortedMultiSet
def rangeImpl(from: Option[A], until: Option[A]): SortedMultiSet[A] =
new SortedMultiSet(elems.rangeImpl(from, until))
/**
* @return an immutable sorted multiset containing all the elements of
* this multiset and one more occurrence of `elem`
* @param elem the element to add
*/
def incl(elem: A): SortedMultiSet[A] =
new SortedMultiSet(elems.updatedWith(elem) {
case None => Some(1)
case Some(n) => Some(n + 1)
})
/** Alias for `incl` */
@`inline` final def + (elem: A): SortedMultiSet[A] = incl(elem)
/**
* @return an immutable sorted multiset containing all the elements of
* this multiset and one occurrence less of `elem`
*
* @param elem the element to remove
*/
def excl(elem: A): SortedMultiSet[A] =
new SortedMultiSet(elems.updatedWith(elem) {
case Some(n) => if (n > 1) Some(n - 1) else None
})
/** Alias for `excl` */
@`inline` final def - (elem: A): SortedMultiSet[A] = excl(elem)
}
object SortedMultiSet extends SortedIterableFactory[SortedMultiSet] {
def from[A: Ordering](source: IterableOnce[A]): SortedMultiSet[A] =
source match {
case sms: SortedMultiSet[A] => sms
case _ => (newBuilder[A]() ++= source).result()
}
def empty[A: Ordering]: SortedMultiSet[A] = new SortedMultiSet[A](TreeMap.empty)
def newBuilder[A: Ordering](): Builder[A, SortedMultiSet[A]] =
new ImmutableBuilder[A, SortedMultiSet[A]](empty) {
def addOne(elem: A): this.type = { elems = elems + elem; this }
}
}