1
votes

I'm trying to write a Julia function, which can accept both 1-dimensional Int64 and Float64 array as input argument. How can I do this without defining two versions, one for Int64 and another for Float64?

I have tried using Array{Real,1} as input argument type. However, since Array{Int64,1} is not a subtype of Array{Real,1}, this cannot work.

1
Have you tried Array{<:Real,1}?ig0774
I've tried, it works. thanks so much. But I am curious why this works? what's the difference between them?user8036269
<:Real specifies that it’s an array containing a subtype of Real, i.e., Julia treats it as a parametric type, if that makes sense...ig0774
See docs.julialang.org/en/latest/manual/types/… for more information and en.wikipedia.org/wiki/… for definitions of invariance and covariance.carstenbauer
Are you most interested in how to work with this design or why the design is like that in the first place?StefanKarpinski

1 Answers

-1
votes

A genuine, non secure way to do it is, with an example:


function square(x)
# The point is for element-wise operation
       out = x.*x
end


Output:

julia> square(2)
4

julia> square([2 2 2])
1×3 Array{Int64,2}:
 4  4  4