You are correct it could act the way you propose, it is a conscious design decision to not go that way. for a in A
will always iterates just the values of A
. You could design/change the language to do the equivalent to for (i, a) in pairs(A)
when you write for (i, a) in A
, and do the equivalent of for (count, (i, a))
when you write for (count, i, a) in enumerate(pairs(A))
. However, this would disallow you to de-structure tuples in the general case, because the syntax would be ambiguous. For example, the following use case would be disallowed (or have its meaning changed):
julia> A = [('a', 10), ('b', 20), ('c', 30)]
3-element Array{Tuple{Char,Int64},1}:
('a', 10)
('b', 20)
('c', 30)
julia> for (a, b) in A; println("$a $b"); end
a 10
b 20
c 30
I do agree with the language design decision here, as I find it to be the more elegant one. Now, any of these iterators that you may want (including the count, i, a
) can be implemented by enumerators instead.
julia> enumpairs(xs) = zip(1:length(xs), eachindex(xs), values(xs))
enumpairs (generic function with 1 method)
julia> using OffsetArrays
julia> oa = OffsetArray(["a", "b", "c", "d", "e"], -2:2)
5-element OffsetArray(::Array{String,1}, -2:2) with eltype String with indices -2:2:
"a"
"b"
"c"
"d"
"e"
julia> for (count, i, a) in enumpairs(oa)
println("$count $i $a")
end
1 -2 a
2 -1 b
3 0 c
4 1 d
5 2 e