Skip to content

Implement getindex, firstindex, and lastindex for Generators #48745

@uniment

Description

@uniment

A generator like this:

(x^2 for x=(1,2,3))

should be indexable:

Base.getindex(g::Base.Generator, args...) = g.f(getindex(g.iter, args...))
Base.firstindex(g::Base.Generator, d...) = firstindex(g.iter, d...)
Base.lastindex(g::Base.Generator, d...) = lastindex(g.iter, d...)

especially considering that eachindex(::Generator) is implemented.

Currently, generators implement last but not lastindex:

julia> last(x^2 for x=(1,2,3))
9

julia> lastindex(x^2 for x=(1,2,3))
ERROR: MethodError: no method matching lastindex(::Base.Generator{Tuple{Int64, Int64, Int64}, var"#7#8"})

This contradicts the user manual:

Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by calling lastindex to get the last index.

So, to be consistent with eachindex, first, and last, generators should also implement getindex, firstindex, and lastindex.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions