David
David

Reputation: 77

Specify type of a vector/array containing any number

Brand new to Julia - so I apologize for the simple question, just couldn't seem to find the answer anywhere:

I am trying to create a function which takes a vector as an argument, but enforces that the vector contains numbers (either floats or ints).

I feel like this should be written as:

function foo(x::Vector{Number})
    return x.^2
end

But running this with foo([5.0]) yields

ERROR: MethodError: no method matching foo(::Array{Float64,1})
Closest candidates are:
   foo(::Array{Number,1}) at REPL[16]:2

Why is this? I don't want to resort to saying x::Vector, which would work, but doesn't provide the type-checking enforcement that I would want.

Upvotes: 0

Views: 92

Answers (1)

DNF
DNF

Reputation: 12644

You can write

function foo(x::Vector{T}) where {T<:Number}
    return x.^2
end

A shorthand notation for this is

function foo(x::Vector{<:Number})
    return x.^2
end

Edit: Based on comments by @Liso and @MichaelKBorregaard I suggest the following, which disallows Complex and allows AbstractVectors:

function foo(x::AbstractVector{<:Real})
    return x.^2
end

If you really only want to allow floats and ints, you can do:

function foo(x::AbstractVector{<:Union{AbstractFloat, Integer}})
    return x.^2
end

You can get pretty much as specific or as general as you like.

Upvotes: 3

Related Questions