Reputation: 55
I want to have a function that takes in an array of numbers and does some operation on them. To do this, I created the function
function squarearray(numinarray::Vector{Number})
numinarray[1]^2
end
But when I tried calling it with
print(squarearray(Vector([1.0])))
it caused an error:
ERROR: LoadError: MethodError: no method matching squarearray(::Vector{Float64})
Closest candidates are:
squarearray(::Vector{Number}) at ~/Programming/ai/structlearn.jl:7
squarearray(::AbstractVector{Number}) at ~/Programming/ai/structlearn.jl:7
Float64
is a subtype of Number
, so why won't this work? I know I could specify in the function that it takes in in array of floats, but I also want the function to work on ints.
Thanks!
-Diego
Upvotes: 1
Views: 182
Reputation: 563
The "Number" Type is Abstract. This means no data can be directly of type Number. However, as you pointed out, Number has concrete subtypes, such as Float64. If you change
numinarray::Vector{<:Number} #limits to only subtypes of Number
or
numinarray::Vector{Float64} #limits to Float64 type
or
numinarray::Vector #Does not limit inputs
You should avoid the problem.
Upvotes: 3