Skip to content

Commit

Permalink
datatypes: fix for set - operator, union and intersection, now they…
Browse files Browse the repository at this point in the history
… no longer change the receiver (fix #21315) (#21362)
  • Loading branch information
felipensp authored May 1, 2024
1 parent 794e238 commit 6f7f7e0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
6 changes: 3 additions & 3 deletions vlib/datatypes/set.v
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ pub fn (mut set Set[T]) add_all(elements []T) {

// @union returns the union of the two sets.
pub fn (l Set[T]) @union(r Set[T]) Set[T] {
mut set := l
mut set := l.copy()
for e, _ in r.elements {
set.add(e)
}
Expand All @@ -94,7 +94,7 @@ pub fn (l Set[T]) @union(r Set[T]) Set[T] {

// intersection returns the intersection of sets.
pub fn (l Set[T]) intersection(r Set[T]) Set[T] {
mut set := l
mut set := l.copy()
for e, _ in l.elements {
if !r.exists(e) {
set.remove(e)
Expand All @@ -110,7 +110,7 @@ pub fn (l Set[T]) intersection(r Set[T]) Set[T] {

// - returns the difference of sets.
pub fn (l Set[T]) - (r Set[T]) Set[T] {
mut set := l
mut set := l.copy()
for e, _ in l.elements {
if r.exists(e) {
set.remove(e)
Expand Down
16 changes: 16 additions & 0 deletions vlib/datatypes/set_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ fn test_union() {
first_set.add_all(['b', 'c', 'd'])
second_set.add_all(['a', 'e'])
mut third_set := first_set.@union(second_set)
assert first_set.elements.len == 3
assert third_set.exists('a')
assert third_set.exists('b')
assert third_set.exists('c')
Expand All @@ -80,6 +81,7 @@ fn test_intersection() {
mut second_set := Set[string]{}
second_set.add_all(['bar', 'baz', 'boo'])
mut third_set := first_set.intersection(second_set)
assert first_set.exists('foo') == true
assert third_set.exists('foo') == false
assert third_set.exists('bar')
assert third_set.exists('baz')
Expand Down Expand Up @@ -108,6 +110,20 @@ fn test_difference() {
assert third_set.exists('boo')
}

fn test_diff() {
m := ['a', 'b', 'c']
n := ['a', 'b', 'c']
assert m == n
mut set_m := Set[string]{}
mut set_n := Set[string]{}
set_m.add_all(m)
set_n.add_all(n)
assert set_m == set_n
diff1 := set_m - set_n
diff2 := set_n - set_m
assert diff1 == diff2
}

fn test_subset() {
mut set := Set[string]{}
set.add_all(['a', 'b', 'c'])
Expand Down

0 comments on commit 6f7f7e0

Please sign in to comment.