OP UPDATE: Note that in the latest version of Julia (v0.5), the idiomatic approach to answering this question is to just define mysquare(x::Number) =
Julia compiles a specific version of your function for each set of inputs as required. Thus to answer part 1, there is no performance difference. The parametric way is the way to go.
As for part 2, it might be a good idea in some cases to write a separate version (sometimes for performance reasons, e.g., to avoid a copy). In your case however you can use the in-built macro @vectorize_1arg
to automatically generate the array version, e.g.:
function mysquare{T<:Number}(x::T)
return(x^2)
end
@vectorize_1arg Number mysquare
println(mysquare([1,2,3]))
As for general style, don't use semicolons, and mysquare(x::Number) = x^2
is a lot shorter.
As for your vectorized mysquare
, consider the case where T
is a BigFloat
. Your output array, however, is Float64
. One way to handle this would be to change it to
function mysquare{T<:Number}(x::Array{T,1})
n = length(x)
y = Array(T, n)
for k = 1:n
@inbounds y[k] = x[k]^2
end
return y
end
where I've added the @inbounds
macro to boost speed because we don't need to check the bound violation every time — we know the lengths. This function could still have issues in the event that the type of x[k]^2
isn't T
. An even more defensive version would perhaps be
function mysquare{T<:Number}(x::Array{T,1})
n = length(x)
y = Array(typeof(one(T)^2), n)
for k = 1:n
@inbounds y[k] = x[k]^2
end
return y
end
where one(T)
would give 1
if T
is an Int
, and 1.0
if T
is a Float64
, and so on. These considerations only matter if you want to make hyper-robust library code. If you really only will be dealing with Float64
s or things that can be promoted to Float64
s, then it isn't an issue. It seems like hard work, but the power is amazing. You can always just settle for Python-like performance and disregard all type information.