2

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.

  • 2
    Have you tried `Array{<:Real,1}`? – ig0774 Jun 24 '19 at 11:28
  • I've tried, it works. thanks so much. But I am curious why this works? what's the difference between them? – user8036269 Jun 24 '19 at 11:34
  • `<: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 Jun 24 '19 at 11:41
  • 2
    See https://docs.julialang.org/en/latest/manual/types/#Parametric-Composite-Types-1 for more information and https://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29#Formal_definition for definitions of invariance and covariance. – carstenbauer Jun 24 '19 at 11:57
  • 1
    Are you most interested in how to work with this design or why the design is like that in the first place? – StefanKarpinski Jun 24 '19 at 14:25
  • This is kinda-sorta a dupe of https://stackoverflow.com/questions/21465838/vectorabstractstring-function-parameter-wont-accept-vectorstring-input-in-j but that answer doesn't cover the "why" – mbauman Jun 24 '19 at 16:34

1 Answers1

-1

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

Cailloumax
  • 260
  • 1
  • 9