Skip to content

Commit

Permalink
Base: intersect keep the container type (#42396)
Browse files Browse the repository at this point in the history
A bug was introduced for 3 arguments version of `intersect` in #41769.
The container type always changed to `Set`:

```
julia> intersect(BitSet([1,2]), [1,2], [2])
Set{Int64} with 1 element:
  2
```

This is an attempt to return to the original behavior:

```
julia> intersect(BitSet([1,2]), [1,2], [2])
BitSet with 1 element:
  2
```
  • Loading branch information
barucden authored Oct 10, 2021
1 parent ad5a13b commit e95f949
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion base/abstractset.jl
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,13 @@ Set{Int64} with 1 element:
"""
function intersect(s::AbstractSet, itr, itrs...)
T = promote_eltype(s, itr, itrs...)
return intersect!(Set{T}(s), itr, itrs...)
if T == promote_eltype(s, itr)
out = intersect(s, itr)
else
out = union!(emptymutable(s, T), s)
intersect!(out, itr)
end
return intersect!(out, itrs...)
end
intersect(s) = union(s)
intersect(s::AbstractSet, itr) = mapfilter(in(s), push!, itr, emptymutable(s, promote_eltype(s, itr)))
Expand Down
6 changes: 6 additions & 0 deletions test/sets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ end
end
@test intersect(Set([1]), BitSet()) isa Set{Int}
@test intersect(BitSet([1]), Set()) isa Set{Any}
@test intersect(BitSet([1]), Set([1])) isa BitSet
@test intersect(BitSet([1]), Set([1]), Set([1])) isa BitSet
@test intersect([1], BitSet()) isa Vector{Int}
# intersect must uniquify
@test intersect([1, 2, 1]) == intersect!([1, 2, 1]) == [1, 2]
Expand All @@ -276,6 +278,10 @@ end
@test eltype(intersect(a, a, b)) == Float64
end
end

# 3-argument version is correctly covered
@test intersect(Set([1,2]), Set([2]), Set([1,2,3])) == Set([2])
@test intersect(Set([1,2]), Set([2]), Set([1.,2,3])) == Set([2.])
end

@testset "setdiff" begin
Expand Down

0 comments on commit e95f949

Please sign in to comment.