Skip to content

Commit 29e0a3e

Browse files
LilithHafnerKristofferC
authored andcommitted
Replace some occurrences of iteration over 1:length with more idiomatic structures (mostly eachindex) (#55137)
Base should be a model for the ecosystem, and `eachindex(x)` is better than `1:length(x)` in almost all cases. I've updated many, but certainly not all examples. This is mostly a NFC, but also fixes #55136. (cherry picked from commit 0945b9d)
1 parent cf965f3 commit 29e0a3e

File tree

9 files changed

+25
-26
lines changed

9 files changed

+25
-26
lines changed

base/abstractarray.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1634,10 +1634,10 @@ typed_vcat(::Type{T}) where {T} = Vector{T}()
16341634
typed_hcat(::Type{T}) where {T} = Vector{T}()
16351635

16361636
## cat: special cases
1637-
vcat(X::T...) where {T} = T[ X[i] for i=1:length(X) ]
1638-
vcat(X::T...) where {T<:Number} = T[ X[i] for i=1:length(X) ]
1639-
hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=1:length(X) ]
1640-
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=1:length(X) ]
1637+
vcat(X::T...) where {T} = T[ X[i] for i=eachindex(X) ]
1638+
vcat(X::T...) where {T<:Number} = T[ X[i] for i=eachindex(X) ]
1639+
hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=eachindex(X) ]
1640+
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=eachindex(X) ]
16411641

16421642
vcat(X::Number...) = hvcat_fill!(Vector{promote_typeof(X...)}(undef, length(X)), X)
16431643
hcat(X::Number...) = hvcat_fill!(Matrix{promote_typeof(X...)}(undef, 1,length(X)), X)

base/errorshow.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ function showerror(io::IO, ex::CanonicalIndexError)
196196
print(io, "CanonicalIndexError: ", ex.func, " not defined for ", ex.type)
197197
end
198198

199-
typesof(@nospecialize args...) = Tuple{Any[ Core.Typeof(args[i]) for i in 1:length(args) ]...}
199+
typesof(@nospecialize args...) = Tuple{Any[Core.Typeof(arg) for arg in args]...}
200200

201201
function print_with_compare(io::IO, @nospecialize(a::DataType), @nospecialize(b::DataType), color::Symbol)
202202
if a.name === b.name
@@ -273,7 +273,7 @@ function showerror(io::IO, ex::MethodError)
273273
arg_types_param = arg_types_param[3:end]
274274
san_arg_types_param = san_arg_types_param[3:end]
275275
keys = kwt.parameters[1]::Tuple
276-
kwargs = Any[(keys[i], fieldtype(kwt, i)) for i in 1:length(keys)]
276+
kwargs = Any[(keys[i], fieldtype(kwt, i)) for i in eachindex(keys)]
277277
arg_types = rewrap_unionall(Tuple{arg_types_param...}, arg_types)
278278
end
279279
if f === Base.convert && length(arg_types_param) == 2 && !is_arg_types
@@ -687,7 +687,7 @@ function show_reduced_backtrace(io::IO, t::Vector)
687687

688688
push!(repeated_cycle, (0,0,0)) # repeated_cycle is never empty
689689
frame_counter = 1
690-
for i in 1:length(displayed_stackframes)
690+
for i in eachindex(displayed_stackframes)
691691
(frame, n) = displayed_stackframes[i]
692692

693693
print_stackframe(io, frame_counter, frame, n, ndigits_max, STACKTRACE_FIXEDCOLORS, STACKTRACE_MODULECOLORS)
@@ -864,7 +864,7 @@ end
864864
function _collapse_repeated_frames(trace)
865865
kept_frames = trues(length(trace))
866866
last_frame = nothing
867-
for i in 1:length(trace)
867+
for i in eachindex(trace)
868868
frame::StackFrame, _ = trace[i]
869869
if last_frame !== nothing && frame.file == last_frame.file && frame.line == last_frame.line
870870
#=
@@ -909,7 +909,7 @@ function _collapse_repeated_frames(trace)
909909
end
910910
if length(last_params) > length(params)
911911
issame = true
912-
for i = 1:length(params)
912+
for i = eachindex(params)
913913
issame &= params[i] == last_params[i]
914914
end
915915
if issame

base/expr.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ function copy_exprs(@nospecialize(x))
6868
end
6969
return x
7070
end
71-
copy_exprargs(x::Array{Any,1}) = Any[copy_exprs(@inbounds x[i]) for i in 1:length(x)]
71+
copy_exprargs(x::Array{Any,1}) = Any[copy_exprs(@inbounds x[i]) for i in eachindex(x)]
7272

7373
@eval exprarray(head::Symbol, arg::Array{Any,1}) = $(Expr(:new, :Expr, :head, :arg))
7474

base/intfuncs.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -976,7 +976,7 @@ end
976976
977977
Return an array with element type `T` (default `Int`) of the digits of `n` in the given
978978
base, optionally padded with zeros to a specified size. More significant digits are at
979-
higher indices, such that `n == sum(digits[k]*base^(k-1) for k=1:length(digits))`.
979+
higher indices, such that `n == sum(digits[k]*base^(k-1) for k in eachindex(digits))`.
980980
981981
See also [`ndigits`](@ref), [`digits!`](@ref),
982982
and for base 2 also [`bitstring`](@ref), [`count_ones`](@ref).

base/loading.jl

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1228,7 +1228,7 @@ function _include_from_serialized(pkg::PkgId, path::String, ocachepath::Union{No
12281228
t_comp_before = cumulative_compile_time_ns()
12291229
end
12301230

1231-
for i in 1:length(depmods)
1231+
for i in eachindex(depmods)
12321232
dep = depmods[i]
12331233
dep isa Module && continue
12341234
_, depkey, depbuild_id = dep::Tuple{String, PkgId, UInt128}
@@ -1781,8 +1781,7 @@ function compilecache_path(pkg::PkgId;
17811781
end
17821782
staledeps, _, _ = staledeps::Tuple{Vector{Any}, Union{Nothing, String}, UInt128}
17831783
# finish checking staledeps module graph
1784-
for i in 1:length(staledeps)
1785-
dep = staledeps[i]
1784+
for dep in staledeps
17861785
dep isa Module && continue
17871786
modpath, modkey, modbuild_id = dep::Tuple{String, PkgId, UInt128}
17881787
modpaths = find_all_in_cache_path(modkey)
@@ -1971,7 +1970,7 @@ end
19711970
try
19721971
staledeps, ocachefile, newbuild_id = staledeps::Tuple{Vector{Any}, Union{Nothing, String}, UInt128}
19731972
# finish checking staledeps module graph
1974-
for i in 1:length(staledeps)
1973+
for i in eachindex(staledeps)
19751974
dep = staledeps[i]
19761975
dep isa Module && continue
19771976
modpath, modkey, modbuild_id = dep::Tuple{String, PkgId, UInt128}
@@ -2003,7 +2002,7 @@ end
20032002
end
20042003
# finish loading module graph into staledeps
20052004
# TODO: call all start_loading calls (in reverse order) before calling any _include_from_serialized, since start_loading will drop the loading lock
2006-
for i in 1:length(staledeps)
2005+
for i in eachindex(staledeps)
20072006
dep = staledeps[i]
20082007
dep isa Module && continue
20092008
modpath, modkey, modbuild_id, modcachepath, modstaledeps, modocachepath = dep::Tuple{String, PkgId, UInt128, String, Vector{Any}, Union{Nothing, String}}

base/multidimensional.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1639,7 +1639,7 @@ function checkdims_perm(P::AbstractArray{TP,N}, B::AbstractArray{TB,N}, perm) wh
16391639
length(perm) == N || throw(ArgumentError("expected permutation of size $N, but length(perm)=$(length(perm))"))
16401640
isperm(perm) || throw(ArgumentError("input is not a permutation"))
16411641
indsP = axes(P)
1642-
for i = 1:length(perm)
1642+
for i in eachindex(perm)
16431643
indsP[i] == indsB[perm[i]] || throw(DimensionMismatch("destination tensor of incorrect size"))
16441644
end
16451645
nothing

base/reflection.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2367,7 +2367,7 @@ function hasmethod(f, t, kwnames::Tuple{Vararg{Symbol}}; world::UInt=get_world_c
23672367
for kw in kws
23682368
endswith(String(kw), "...") && return true
23692369
end
2370-
kwnames = Symbol[kwnames[i] for i in 1:length(kwnames)]
2370+
kwnames = collect(kwnames)
23712371
return issubset(kwnames, kws)
23722372
end
23732373

base/show.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -676,7 +676,7 @@ function show_can_elide(p::TypeVar, wheres::Vector, elide::Int, env::SimpleVecto
676676
has_typevar(v.lb, p) && return false
677677
has_typevar(v.ub, p) && return false
678678
end
679-
for i = 1:length(env)
679+
for i = eachindex(env)
680680
i == skip && continue
681681
has_typevar(env[i], p) && return false
682682
end
@@ -1183,7 +1183,7 @@ end
11831183

11841184
function show_at_namedtuple(io::IO, syms::Tuple, types::DataType)
11851185
first = true
1186-
for i in 1:length(syms)
1186+
for i in eachindex(syms)
11871187
if !first
11881188
print(io, ", ")
11891189
end
@@ -2372,7 +2372,7 @@ function show_unquoted(io::IO, ex::Expr, indent::Int, prec::Int, quote_level::In
23722372
if get(io, beginsym, false)
23732373
print(io, '(')
23742374
ind = indent + indent_width
2375-
for i = 1:length(ex.args)
2375+
for i = eachindex(ex.args)
23762376
if i > 1
23772377
# if there was only a comment before the first semicolon, the expression would get parsed as a NamedTuple
23782378
if !(i == 2 && ex.args[1] isa LineNumberNode)
@@ -2890,7 +2890,7 @@ function dump(io::IOContext, x::SimpleVector, n::Int, indent)
28902890
end
28912891
print(io, "SimpleVector")
28922892
if n > 0
2893-
for i = 1:length(x)
2893+
for i in eachindex(x)
28942894
println(io)
28952895
print(io, indent, " ", i, ": ")
28962896
if isassigned(x,i)
@@ -3000,7 +3000,7 @@ function dump(io::IOContext, x::DataType, n::Int, indent)
30003000
end
30013001
fields = fieldnames(x)
30023002
fieldtypes = datatype_fieldtypes(x)
3003-
for idx in 1:length(fields)
3003+
for idx in eachindex(fields)
30043004
println(io)
30053005
print(io, indent, " ", fields[idx])
30063006
if isassigned(fieldtypes, idx)

base/tuple.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -502,7 +502,7 @@ end
502502
_findfirst_rec(f, i::Int, ::Tuple{}) = nothing
503503
_findfirst_rec(f, i::Int, t::Tuple) = (@inline; f(first(t)) ? i : _findfirst_rec(f, i+1, tail(t)))
504504
function _findfirst_loop(f::Function, t)
505-
for i in 1:length(t)
505+
for i in eachindex(t)
506506
f(t[i]) && return i
507507
end
508508
return nothing
@@ -536,7 +536,7 @@ function _isequal(t1::Tuple{Any,Vararg{Any}}, t2::Tuple{Any,Vararg{Any}})
536536
return isequal(t1[1], t2[1]) && _isequal(tail(t1), tail(t2))
537537
end
538538
function _isequal(t1::Any32, t2::Any32)
539-
for i = 1:length(t1)
539+
for i in eachindex(t1, t2)
540540
if !isequal(t1[i], t2[i])
541541
return false
542542
end
@@ -567,7 +567,7 @@ function _eq_missing(t1::Tuple, t2::Tuple)
567567
end
568568
function _eq(t1::Any32, t2::Any32)
569569
anymissing = false
570-
for i = 1:length(t1)
570+
for i in eachindex(t1, t2)
571571
eq = (t1[i] == t2[i])
572572
if ismissing(eq)
573573
anymissing = true

0 commit comments

Comments
 (0)