I would like to know the return type of
similar(A, T, sz) in a type-stable way, without any allocations.
For example, the following method does what I want:
function similartype(A, T, sz::Dims) B = similar(A, T, map(zero, sz)) return typeof(B) end
but the allocation of the array B, even if it has length zero, will not be eliminated (I assume this happens because allocating an Array is not a native Julia operation but calls out to C?).
My use case is the following. Over at TensorOperations.jl, I am experimenting with a module global cache dictionoray to hold temporary arrays used for intermediate results when performing tensor contractions. However, since these temporaries can be of any type, the dictionary (its actually an LRUCache) has
valtype == Any. Say I get a possible temporary array
B from the cache, it’s type cannot be inferred and is
Any. But I would then like to pass this through a function, say
checked_similar(B, A, T, sz), which checks if
B fullfills the requirements, if not, allocates a new temporary, and if so, just returns
B but with the correct type annotated.
So something like
checked_similar(B, A, T, sz) if B !== nothing && size(B) == sz && eltype(B) == T TB = similartype(A, T, sz) return B::TB else return similar(A, T, sz) end end
Unfortunately, I do not know how to implement
similartype without it actually allocating something.