Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

datatypes: set - operator implementation changes original set #21362

Merged
merged 2 commits into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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