Skip to content

Define length(::Iterators.Rest{<:AbstractVector}) #60343

@mtfishman

Description

@mtfishman

length(::Iterators.Rest{<:AbstractVector}) currently isn't defined, which affects these kinds of use cases:

julia> length(Iterators.rest([1, 2, 3, 4], 2))
ERROR: MethodError: no method matching length(::Base.Iterators.Rest{Vector{Int64}, Int64})
The function `length` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  length(::Base.EnvDict)
   @ Base env.jl:232
  length(::BitSet)
   @ Base bitset.jl:355
  length(::Base.MethodSpecializations)
   @ Base runtime_internals.jl:1877
  ...

Stacktrace:
 [1] top-level scope
   @ REPL[1]:1

julia> length(Iterators.peel([1, 2, 3, 4])[2])
ERROR: MethodError: no method matching length(::Base.Iterators.Rest{Vector{Int64}, Int64})
The function `length` exists, but no method is defined for this combination of argument types.

Closest candidates are:
  length(::Base.EnvDict)
   @ Base env.jl:232
  length(::BitSet)
   @ Base bitset.jl:355
  length(::Base.MethodSpecializations)
   @ Base runtime_internals.jl:1877
  ...

Stacktrace:
 [1] top-level scope
   @ REPL[1]:1

julia> versioninfo()
Julia Version 1.14.0-DEV.1286
Commit fd419bd9233 (2025-11-23 16:30 UTC)
Build Info:
  Official https://julialang.org release
Platform Info:
  OS: macOS (arm64-apple-darwin24.0.0)
  CPU: 10 × Apple M1 Max
  WORD_SIZE: 64
  LLVM: libLLVM-20.1.8 (ORCJIT, apple-m1)
  GC: Built with stock GC
Threads: 1 default, 1 interactive, 1 GC (on 8 virtual cores)
Environment:
  JULIA_EDITOR = code

I understand that length(::Iterator.Rest) isn't defined for general iterators since the length may not be efficiently computable from the state, but it seems like for vectors it is reasonable to define it. I could imagine a definition like:

function Base.length(itr::Iterators.Rest{T}) where {T<:AbstractVector}
    len = length(itr.itr) - itr.st + 1
    return max(len, zero(len))
end

but maybe there is something I'm not considering.

Metadata

Metadata

Assignees

No one assigned

    Labels

    arrays[a, r, r, a, y, s]featureIndicates new feature / enhancement requestsiterationInvolves iteration or the iteration protocol

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions