Skip to content

Commit 0945b9d

Browse files
authored
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.
1 parent 742e7d9 commit 0945b9d

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
@@ -1659,10 +1659,10 @@ typed_vcat(::Type{T}) where {T} = Vector{T}()
16591659
typed_hcat(::Type{T}) where {T} = Vector{T}()
16601660

16611661
## cat: special cases
1662-
vcat(X::T...) where {T} = T[ X[i] for i=1:length(X) ]
1663-
vcat(X::T...) where {T<:Number} = T[ X[i] for i=1:length(X) ]
1664-
hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=1:length(X) ]
1665-
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=1:length(X) ]
1662+
vcat(X::T...) where {T} = T[ X[i] for i=eachindex(X) ]
1663+
vcat(X::T...) where {T<:Number} = T[ X[i] for i=eachindex(X) ]
1664+
hcat(X::T...) where {T} = T[ X[j] for i=1:1, j=eachindex(X) ]
1665+
hcat(X::T...) where {T<:Number} = T[ X[j] for i=1:1, j=eachindex(X) ]
16661666

16671667
vcat(X::Number...) = hvcat_fill!(Vector{promote_typeof(X...)}(undef, length(X)), X)
16681668
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
@@ -694,7 +694,7 @@ function show_reduced_backtrace(io::IO, t::Vector)
694694

695695
push!(repeated_cycle, (0,0,0)) # repeated_cycle is never empty
696696
frame_counter = 1
697-
for i in 1:length(displayed_stackframes)
697+
for i in eachindex(displayed_stackframes)
698698
(frame, n) = displayed_stackframes[i]
699699

700700
print_stackframe(io, frame_counter, frame, n, ndigits_max, STACKTRACE_FIXEDCOLORS, STACKTRACE_MODULECOLORS)
@@ -871,7 +871,7 @@ end
871871
function _collapse_repeated_frames(trace)
872872
kept_frames = trues(length(trace))
873873
last_frame = nothing
874-
for i in 1:length(trace)
874+
for i in eachindex(trace)
875875
frame::StackFrame, _ = trace[i]
876876
if last_frame !== nothing && frame.file == last_frame.file && frame.line == last_frame.line
877877
#=
@@ -916,7 +916,7 @@ function _collapse_repeated_frames(trace)
916916
end
917917
if length(last_params) > length(params)
918918
issame = true
919-
for i = 1:length(params)
919+
for i = eachindex(params)
920920
issame &= params[i] == last_params[i]
921921
end
922922
if issame

base/expr.jl

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

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

base/intfuncs.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -978,7 +978,7 @@ end
978978
979979
Return an array with element type `T` (default `Int`) of the digits of `n` in the given
980980
base, optionally padded with zeros to a specified size. More significant digits are at
981-
higher indices, such that `n == sum(digits[k]*base^(k-1) for k=1:length(digits))`.
981+
higher indices, such that `n == sum(digits[k]*base^(k-1) for k in eachindex(digits))`.
982982
983983
See also [`ndigits`](@ref), [`digits!`](@ref),
984984
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
@@ -1214,7 +1214,7 @@ function _include_from_serialized(pkg::PkgId, path::String, ocachepath::Union{No
12141214
t_comp_before = cumulative_compile_time_ns()
12151215
end
12161216

1217-
for i in 1:length(depmods)
1217+
for i in eachindex(depmods)
12181218
dep = depmods[i]
12191219
dep isa Module && continue
12201220
_, depkey, depbuild_id = dep::Tuple{String, PkgId, UInt128}
@@ -1706,8 +1706,7 @@ function compilecache_path(pkg::PkgId;
17061706
end
17071707
staledeps, _, _ = staledeps::Tuple{Vector{Any}, Union{Nothing, String}, UInt128}
17081708
# finish checking staledeps module graph
1709-
for i in 1:length(staledeps)
1710-
dep = staledeps[i]
1709+
for dep in staledeps
17111710
dep isa Module && continue
17121711
modpath, modkey, modbuild_id = dep::Tuple{String, PkgId, UInt128}
17131712
modpaths = find_all_in_cache_path(modkey)
@@ -1897,7 +1896,7 @@ end
18971896
try
18981897
staledeps, ocachefile, newbuild_id = staledeps::Tuple{Vector{Any}, Union{Nothing, String}, UInt128}
18991898
# finish checking staledeps module graph
1900-
for i in 1:length(staledeps)
1899+
for i in eachindex(staledeps)
19011900
dep = staledeps[i]
19021901
dep isa Module && continue
19031902
modpath, modkey, modbuild_id = dep::Tuple{String, PkgId, UInt128}
@@ -1929,7 +1928,7 @@ end
19291928
end
19301929
# finish loading module graph into staledeps
19311930
# TODO: call all start_loading calls (in reverse order) before calling any _include_from_serialized, since start_loading will drop the loading lock
1932-
for i in 1:length(staledeps)
1931+
for i in eachindex(staledeps)
19331932
dep = staledeps[i]
19341933
dep isa Module && continue
19351934
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
@@ -1674,7 +1674,7 @@ function checkdims_perm(P::AbstractArray{TP,N}, B::AbstractArray{TB,N}, perm) wh
16741674
length(perm) == N || throw(ArgumentError("expected permutation of size $N, but length(perm)=$(length(perm))"))
16751675
isperm(perm) || throw(ArgumentError("input is not a permutation"))
16761676
indsP = axes(P)
1677-
for i = 1:length(perm)
1677+
for i in eachindex(perm)
16781678
indsP[i] == indsB[perm[i]] || throw(DimensionMismatch("destination tensor of incorrect size"))
16791679
end
16801680
nothing

base/reflection.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2425,7 +2425,7 @@ function hasmethod(f, t, kwnames::Tuple{Vararg{Symbol}}; world::UInt=get_world_c
24252425
for kw in kws
24262426
endswith(String(kw), "...") && return true
24272427
end
2428-
kwnames = Symbol[kwnames[i] for i in 1:length(kwnames)]
2428+
kwnames = collect(kwnames)
24292429
return issubset(kwnames, kws)
24302430
end
24312431

base/show.jl

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -681,7 +681,7 @@ function show_can_elide(p::TypeVar, wheres::Vector, elide::Int, env::SimpleVecto
681681
has_typevar(v.lb, p) && return false
682682
has_typevar(v.ub, p) && return false
683683
end
684-
for i = 1:length(env)
684+
for i = eachindex(env)
685685
i == skip && continue
686686
has_typevar(env[i], p) && return false
687687
end
@@ -1188,7 +1188,7 @@ end
11881188

11891189
function show_at_namedtuple(io::IO, syms::Tuple, types::DataType)
11901190
first = true
1191-
for i in 1:length(syms)
1191+
for i in eachindex(syms)
11921192
if !first
11931193
print(io, ", ")
11941194
end
@@ -2382,7 +2382,7 @@ function show_unquoted(io::IO, ex::Expr, indent::Int, prec::Int, quote_level::In
23822382
if get(io, beginsym, false)
23832383
print(io, '(')
23842384
ind = indent + indent_width
2385-
for i = 1:length(ex.args)
2385+
for i = eachindex(ex.args)
23862386
if i > 1
23872387
# if there was only a comment before the first semicolon, the expression would get parsed as a NamedTuple
23882388
if !(i == 2 && ex.args[1] isa LineNumberNode)
@@ -2904,7 +2904,7 @@ function dump(io::IOContext, x::SimpleVector, n::Int, indent)
29042904
end
29052905
print(io, "SimpleVector")
29062906
if n > 0
2907-
for i = 1:length(x)
2907+
for i in eachindex(x)
29082908
println(io)
29092909
print(io, indent, " ", i, ": ")
29102910
if isassigned(x,i)
@@ -3021,7 +3021,7 @@ function dump(io::IOContext, x::DataType, n::Int, indent)
30213021
end
30223022
fields = fieldnames(x)
30233023
fieldtypes = datatype_fieldtypes(x)
3024-
for idx in 1:length(fields)
3024+
for idx in eachindex(fields)
30253025
println(io)
30263026
print(io, indent, " ")
30273027
is_mut && isconst(x, idx) && print(io, "const ")

base/tuple.jl

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -503,7 +503,7 @@ end
503503
_findfirst_rec(f, i::Int, ::Tuple{}) = nothing
504504
_findfirst_rec(f, i::Int, t::Tuple) = (@inline; f(first(t)) ? i : _findfirst_rec(f, i+1, tail(t)))
505505
function _findfirst_loop(f::Function, t)
506-
for i in 1:length(t)
506+
for i in eachindex(t)
507507
f(t[i]) && return i
508508
end
509509
return nothing
@@ -537,7 +537,7 @@ function _isequal(t1::Tuple{Any,Vararg{Any}}, t2::Tuple{Any,Vararg{Any}})
537537
return isequal(t1[1], t2[1]) && _isequal(tail(t1), tail(t2))
538538
end
539539
function _isequal(t1::Any32, t2::Any32)
540-
for i = 1:length(t1)
540+
for i in eachindex(t1, t2)
541541
if !isequal(t1[i], t2[i])
542542
return false
543543
end
@@ -568,7 +568,7 @@ function _eq_missing(t1::Tuple, t2::Tuple)
568568
end
569569
function _eq(t1::Any32, t2::Any32)
570570
anymissing = false
571-
for i = 1:length(t1)
571+
for i in eachindex(t1, t2)
572572
eq = (t1[i] == t2[i])
573573
if ismissing(eq)
574574
anymissing = true

0 commit comments

Comments
 (0)