So, is there a preferred way for for i = 1:5 ... end
with N
known to the compiler, that permits type-instability with respect to i
?
That is, each iteration might have entirely different types, and might need entirely different optimizations. But it might also be possible to make it a loop, who knows.
For example, a natural way of implementing ntuple
could be:
julia> function mk_ntup(f, ::Val{N}) where N
res = ()
for i=1:N
res = (res..., f(i))
end
return res
end
But that does not cut the cake: The return value for e.g. mk_ntup(identity, Val(5))
is inferred as Tuple{Vararg{Int64,N} where N}
.
A macro like @repeat i = 1:N
could do the job, but would be worse if there are no instabilities: Then, it is faster to compile and probably faster to execute as a loop, i.e. with a loop counter and branches back; anyways, it is llvm’s job to know whether to unroll a loop or not (trade off decoding time, code size, L1i vs cost of loop-counter, branch, advantages of using immediates).