Skip to content

Commit 82a2898

Browse files
committed
Add functionality to SimpleIdentitySet
1 parent ea4e06a commit 82a2898

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

compiler/src/dotty/tools/dotc/util/SimpleIdentitySet.scala

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,28 +7,45 @@ import collection.mutable
77
*/
88
abstract class SimpleIdentitySet[+Elem <: AnyRef] {
99
def size: Int
10-
final def isEmpty: Boolean = size == 0
1110
def + [E >: Elem <: AnyRef](x: E): SimpleIdentitySet[E]
1211
def - [E >: Elem <: AnyRef](x: E): SimpleIdentitySet[Elem]
1312
def contains[E >: Elem <: AnyRef](x: E): Boolean
1413
def foreach(f: Elem => Unit): Unit
1514
def exists[E >: Elem <: AnyRef](p: E => Boolean): Boolean
1615
def /: [A, E >: Elem <: AnyRef](z: A)(f: (A, E) => A): A
1716
def toList: List[Elem]
17+
18+
final def isEmpty: Boolean = size == 0
19+
20+
def forall[E >: Elem <: AnyRef](p: E => Boolean): Boolean = !exists(!p(_))
21+
22+
def filter(p: Elem => Boolean): SimpleIdentitySet[Elem] =
23+
val z: SimpleIdentitySet[Elem] = SimpleIdentitySet.empty
24+
(z /: this)((s, x) => if p(x) then s + x else s)
25+
1826
def ++ [E >: Elem <: AnyRef](that: SimpleIdentitySet[E]): SimpleIdentitySet[E] =
1927
if (this.size == 0) that
2028
else if (that.size == 0) this
2129
else ((this: SimpleIdentitySet[E]) /: that)(_ + _)
30+
2231
def -- [E >: Elem <: AnyRef](that: SimpleIdentitySet[E]): SimpleIdentitySet[E] =
2332
if (that.size == 0) this
2433
else
2534
((SimpleIdentitySet.empty: SimpleIdentitySet[E]) /: this) { (s, x) =>
2635
if (that.contains(x)) s else s + x
2736
}
28-
override def toString: String = toList.mkString("(", ", ", ")")
37+
override def toString: String = toList.mkString("{", ", ", "}")
2938
}
3039

3140
object SimpleIdentitySet {
41+
42+
def apply[Elem <: AnyRef](elems: Elem*): SimpleIdentitySet[Elem] =
43+
elems.foldLeft(empty: SimpleIdentitySet[Elem])(_ + _)
44+
45+
extension [E <: AnyRef](xs: SimpleIdentitySet[E])
46+
def intersect(ys: SimpleIdentitySet[E]): SimpleIdentitySet[E] =
47+
xs.filter(ys.contains)
48+
3249
object empty extends SimpleIdentitySet[Nothing] {
3350
def size: Int = 0
3451
def + [E <: AnyRef](x: E): SimpleIdentitySet[E] =

0 commit comments

Comments
 (0)