Vector of vectors supertype

I would like to define a function that takes arguments of the type Vector{Vector{Float64}} but is also not restricted to just Float64s (e.g. it should also be able take arguments of type Vector{Vector{Int64}}).

However, if I try and define the function with a more generic type, like here:

julia> x = [[1.0, 2.0],[0.1, 0.2]]
2-element Vector{Vector{Float64}}:
 [1.0, 2.0]
 [0.1, 0.2]

julia> foo(v::Vector{Vector}) = return v
foo (generic function with 1 method)

julia> foo(x)
ERROR: MethodError: no method matching foo(::Vector{Vector{Float64}})
Closest candidates are:
  foo(::Vector{Vector}) at REPL[116]:1

This is because Vector{Vector} is not a supertype of Vector{Vector{Float64}}, despite Vector being a supertype of Vector{Float64}.

julia> Vector{Float64} <: Vector

julia> Vector{Vector{Float64}} <: Vector{Vector}

Is there a solution to this, or should I just stick to writing multiple functions for the ‘subtypes’ of Vector{Vector} that are relevant for my program?


foo(v::Vector{<:Vector}) = return v


foo(v::Vector{Vector{T}}) where T = return v
1 Like

julia types are invariant (except Tuple):

julia> Vector{Vector{Float64}} <: Vector{<:AbstractVector}

btw, idk what field of research/computing you’re in, but if this gets large, you might want to consider:

1 Like

Thank you so much! I needed to be more familiar with the syntax for type selectors for this one…

That is very useful to know about, thank you.