Function not able to dispatch to a method I believed was defined

Say I defined

julia> f(x::Number, g) = g(x)
f (generic function with 1 method)

julia> f(x::Array{Number, 1}, g) = f.(x)
f (generic function with 2 methods)

julia> g(x) = 2x
g (generic function with 1 method)

When calling f one method performs as expected but the other one fails to do so:

julia> f(1,g)
2

julia> f([1,1], g)
ERROR: MethodError: no method matching f(::Array{Int64, 1}, typeof(g))
Closest candidates are:
  f(::Number, ::Any) at REPL[7]:1
  f(::Array{Number,1}, ::Any) at REPL[8]:1

What’s more, the body of the second method seems fine:

julia> f.([1,1],g)
2-element Array{Int64,1}:
2
2

So I don’t understand why the second definition of f does not catch the array argument?
Thank you very much in advance for any guidance.

You need to use Array{<:Number, 1} instead of Array{Number}. The problem is that even though Int <: Number is true, Array{Int, 1} <: Array{Number, 1} is false.

5 Likes

Thank you very much!