Hi
Often I would like to initialize an array without specifying an eltype in advance, even though I know all elements of the array will have the same concrete type. By way of example,
function makesomearray()
arr = []
for i in 1:10
element = some_computation(i) #some type stable computation
push!(arr, element)
end
return arr #Array{Any, 1}
end
where element
can have a fairly nontrivial type that is hard to know in advance. Of course, the above code is not performant, since arr
will have type Array{Any, 1}
. In order to make it type stable, I often write something like this:
function makesomearray2()
element = some_computation(1)
arr = [element]
for i in 2:10
element = some_computation(i)
push!(arr, element)
end
return arr #Array{eltype(element), 1}
end
which is ugly. What I much prefer of is some kind of “lazy empty array”, which does not fix its type until a first element is pushed into it, such that the following code, almost identical to makesomearray
will return the correct type.
function makesomearray3()
arr = LazyEmptyArray[]
for i in 1:10
element = some_computation(i)
push!(arr, element) # the first invocation of this should tell the compiler what type arr should be
end
return arr #Array{eltype(element), 1}
end
My questions are
- Is there already some macro or package for handling this kind of logic?
- If not, is there any obstacle to implementing
LazyEmptyArray
?
Thank you!