Julia allows for easy construction of arrays using comprehension syntax:
A = [ sqrt(i)^2+j for i in 0:10, j in 1:3 ]
I assume that for type stable expressions the compiler first determines the type of the generic element, the length of the iterable, and then pre-allocates and initialises the array and its content.
Sometimes, however, a nested for loop is preferred. This could be because the array has many dimensions, or because the second iterable's length depends on the first, or becasue the expression is complicated and computing it has side effects.
In those case the above code can be expanded into
T = ???
A = Array{T}(11,3)
for i in 0:10
for j in 1:3
A[i,j] = sqrt(i)^2 + j
end
end
How can T
be computed in a simple, readable, easily maintainable fashion? Is there a way to manually invoke the type inference mechanism used under the hood of list comprehensions? Solutions I consider unsatisfactory are:
T = Float64 # Not my job to do the compiler's work...
T = typeof(sqrt(0)^2+1) # Or is the argument of typeof not evaluated in this case?
Something along the line of the c++ decltype
mechanism perhaps?