Multiple dispatch with Union of parametric types

Hi, I have a problem with multidispatch. I have a lot of functions defined that take 2 parameters a and b. These may be a vector and a dict, a dict and an int etc. Or e.g. Union{Any, Vector}.
It all seemed to work well until I decided to add a set of functions where any of the parameters is an Array (not Vector). I believe this must be dispatched with parameters so I changed all Vectors to Array{T,1}.

But with the Union type the dispatch doesn’t do what I’d like it to, see example:

d1 = Dict("A" => 1)
d2 = Dict("B" => 2)
d3 = Dict("C" => 3)

function x(a::Array{T,N}, b::Dict) where {T,N}
    throw(DomainError("Do not support any arrays!"))
end

function x(a::Union{Any,Array{T,1}}, b::Dict) where T
    return 1
end

x([d1,d2], d3)

where It throws the DomainError from the first function but I want it to return “1” because [d1,d2] is a Vector! Thanks!

  1. Vector is an alias for Array{T, 1}, so it doesn’t matter how you write it.
  2. Union{Any, Vector{T}} is Any, so you lost Vector specialization.

This is working

function x(a::Array{T,N}, b::Dict) where {T,N}
    throw(DomainError("Do not support any arrays!"))
end

function x(a, b::Dict)
    return 1
end

function x(a::Vector{T}, b::Dict) where T
    return 1
end

julia> x([d1,d2], d3)
1
2 Likes