Why can't I use Vector{Int64} with functions expecting Vector{Integer}?

Hi,
I was trying to define a function that would work on all integer types, and could not get it to work when the input is matrix or vector.

functions taking in single value of Int64 or Integer work fine. But if I call a function expecting Vector{Integer} with input of Vector{Int64} it does not work.

Is there a way to work around this? Or am I doing something wrong here?

f1(x::Integer)  = display(x)
f2(x::Int64)    = display(x)

f1(x::Vector{Integer})  = display(x)
f2(x::Vector{Int64})    = display(x)

v = collect(1:5);

# These work
f1(v[1])
f2(v[1])

# This also works
f2(v)

# But this doesn't
f1(v)

The error I get:

julia> f1(v)
ERROR: MethodError: no method matching f1(::Vector{Int64})
Closest candidates are:
  f1(::Integer) at REPL[34]:1
  f1(::Vector{Integer}) at REPL[36]:1
Stacktrace:
 [1] top-level scope
   @ REPL[45]:1

Thanks,
Titas

Update:

I’ve been trying a couple of different things and thought maybe I should be using AbstractVector for this, however the following:

f3(x::AbstractVector{Integer}) = display(x)

but got the same error.


I then found found the following to work the way I expect:

f6(x::Vector{T} where T = Integer) = display(x)

however, this seems like a bit overcomplicated way to write this out - is there a simpler way?

A shorthand is Vector{<:Integer}.

1 Like

Quick answer (I am typing this from my phone): This is explained in the manual in the section on parametric types.

1 Like

This doesn’t do what you expect it to. I think you expected:

f6(x::Vector{T} where T <: Integer) = display(x)

What you actually had is:

f6( ( x::Vector{T} where T ) = Integer) = display(x)

i.e. f6 takes vector x of any type, and the default value of x is the value Integer. Thus calling f6() invokes f6(Integer) which is undefined.

Use methods(f6) to follow which definitions are active in a session.

2 Likes