I’m having trouble with function dispatch where I want to have two different implementations when the values in a dictionary are vectors or not
These work as I would expect:
function fn(val::Vector{Any})
@info "fn, any vector"
@show typeof(val)
end
function fn(val::Vector)
@info "fn, vector"
@show typeof(val)
end
function fn(val)
@info "fn, scalar"
@show typeof(val)
end
fn(1)
# [ Info: fn, scalar
# typeof(val) = Int64
fn(true)
# [ Info: fn, scalar
# typeof(val) = Bool
fn("foo")
# [ Info: fn, scalar
# typeof(val) = String
fn([1, 2])
# [ Info: fn, vector
# typeof(val) = Vector{Int64}
fn([true, false])
# [ Info: fn, vector
# typeof(val) = Vector{Bool}
fn(["foo", "bar"])
# [ Info: fn, vector
# typeof(val) = Vector{String}
fn([1, "foo"])
# [ Info: fn, any vector
# typeof(val) = Vector{Any}
However in the examples below, I don’t understand how the vector versions of the functions are being picked.
function fn(val::Dict{Symbol,Vector{Any}})
@info "fn, dict of any vector"
@show typeof(val)
end
function fn(val::Dict{Symbol,Vector})
@info "fn, dict of vector"
@show typeof(val)
end
function fn(val::Dict)
@info "fn, dict of scalar"
@show typeof(val)
end
## as expected
fn(Dict(:a => 1, :b => 2))
# [ Info: fn, dict of scalar
# typeof(val) = Dict{Symbol, Int64}
fn(Dict(:a => true, :b => false))
# [ Info: fn, dict of scalar
# typeof(val) = Dict{Symbol, Bool}
fn(Dict(:a => "foo", :b => "bar"))
# [ Info: fn, dict of scalar
# typeof(val) = Dict{Symbol, String}
fn(Dict(:a => [1] , :b => [2]))
# [ Info: fn, dict of scalar <- expected dict of vector
# typeof(val) = Dict{Symbol, Vector{Int64}}
fn(Dict(:a => [true], :b => [false]))
# [ Info: fn, dict of scalar <- expected dict of vector
# typeof(val) = Dict{Symbol, Vector{Bool}}
fn(Dict(:a => ["foo"], :b => ["bar"]))
# [ Info: fn, dict of scalar <- expected dict of vector
# typeof(val) = Dict{Symbol, Vector{String}}
fn(Dict(:a => [1, "foo"], :b => ["bar"]))
# [ Info: fn, dict of vector <- expected dict of any vector
# typeof(val) = Dict{Symbol, Vector}
Can someone help me understand what’s going on, and recommend how should I be typing this? When the dictionary values are vectors, I want to have slightly different behaviour.