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

add method for getindex(::ProductIterator, inds...) #49965

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
1 change: 1 addition & 0 deletions base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,7 @@ end
reverse(p::ProductIterator) = ProductIterator(Base.map(reverse, p.iterators))
last(p::ProductIterator) = Base.map(last, p.iterators)
intersect(a::ProductIterator, b::ProductIterator) = ProductIterator(intersect.(a.iterators, b.iterators))
getindex(p::ProductIterator, inds...) = map(getindex, p.iterators, inds)
MasonProtter marked this conversation as resolved.
Show resolved Hide resolved
Copy link

@FelixBenning FelixBenning Jun 1, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So here is an actual problem with this implementation:

julia> a = Iterators.product([1 2; 3 4], 1:2);

julia> b = collect(a)
2×2×2 Array{Tuple{Int64, Int64}, 3}:
[:, :, 1] =
 (1, 1)  (2, 1)
 (3, 1)  (4, 1)

[:, :, 2] =
 (1, 2)  (2, 2)
 (3, 2)  (4, 2)

julia> b[1,1,1]
(1, 1)

julia> map(getindex, a.iterators, (1,1,1))
ERROR: BoundsError: attempt to access Tuple{} at index [1]
Stacktrace:
 [1] getindex(t::Tuple, i::Int64)
   @ Base ./tuple.jl:29
 [2] map (repeats 3 times)
   @ ./tuple.jl:250 [inlined]
 [3] top-level scope
   @ REPL[24]:1

i.e. map assumes every iterator is one dimensional. The following should be a fix I think

function getindex(prod::ProductIterator, indices...)
    return _prod_getindex(prod.iterators, indices...)
end
_prod_getindex(::Tuple{}) = ()
function _prod_getindex(p_vecs::Tuple, indices...)
    v = first(p_vecs)
    n = ndims(v)
    return (
        v[indices[1:n]...],
        _prod_getindex(Base.tail(p_vecs), indices[n+1:end]...)...
    )
end

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you also need to manage all types of access variants (colons, ranges, ...) if you don't limit indices to Vararg{Int,N}. But for this you need to determine N (i.e. ndims) statically.


# flatten an iterator of iterators

Expand Down