Skip to content

Broadcasting with Set returns an arbitrarily-ordered arrayΒ #33282

@tkf

Description

@tkf

Currently (Julia 1.4-DEV), broadcasting with Set produces a result that relies on iteration order of Set which is not meaningful:

julia> Set([1,2]) .+ Set([3,4])
2-element Array{Int64,1}:
 6
 4

This is due to the fallback to collect in broadcastable definition:

broadcastable(x) = collect(x)

A sensible definition may be to use set arithmetic (ref: JuliaMath/IntervalSets.jl#55) such that, for example,

op.(set1, set2) == Set([op(x, y) for x in set1, y in set2])

holds. However, given that "join" on indices/keys is proposed as a generalized form of broadcasting #25904 (and special handling for singleton axes), it is not clear how taking "product" for broadcasting with Sets can fit in a bigger picture.

So, as a short-term solution, I propose to forbid broadcasting with Sets which can easily be done by defining broadcastable(::AbstractSet), as done with Dicts:

broadcastable(::Union{AbstractDict, NamedTuple}) = throw(ArgumentError("broadcasting over dictionaries and `NamedTuple`s is reserved"))

This, of course, requires core devs to decide that this can be treated as a "minor change."

As a longer-term solution, does it make sense to use set arithmetic (which, I suppose, implementable using the style mechanism)? Is there a guiding principle in which it is natural to have "product" for Sets and "join" for associative data structures (including Arrays)?

Metadata

Metadata

Assignees

No one assigned

    Labels

    broadcastApplying a function over a collectioncollectionsData structures holding multiple items, e.g. sets

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions