Suppose I have a container, a
, could be a Tuple
, a Vector
, or a user-defined subtype of AbstractArray
. Now I want to convert every element of a
to another type, e.g., from Int
s to Float64
. For example, I write a rough function:
convert_eltype(T::Type, a) = map(x -> convert(T, x), a)
This function works fine with Tuple
and Vector
, but not the last one.
julia> using StaticArrays
julia> struct A{T} <: FieldVector{2, T}
x::T
y::T
end
julia> convert_eltype(Float64, A(1, 2))
2-element SArray{Tuple{2},Float64,1,2}:
1.0
2.0
This breaks the container type A
:
julia> f(::A) = 1
f (generic function with 1 method)
julia> f(convert_eltype(Float64, A(1, 2)))
ERROR: MethodError: no method matching f(::SArray{Tuple{2},Float64,1,2})
Closest candidates are:
f(::A) at REPL[7]:1
Stacktrace:
[1] top-level scope at none:0
I also tried other ways:
convert_eltype(T::Type, a) = typeof(a)(map(x -> convert(T, x), a))
But it does not work. typeof(a)
contains the Int
information which makes map(x -> convert(T, x), a)
work in vain.
I try to strip the container type but am told it seems not possible. I do not find similar
useful because it just constructs a new uninitialized container, not converting one type to another.