I am writing some software that involves a library of various functional forms of a quantity. I want to leverage Julia's multiple dispatch, but want to know if there's a more efficient way to implement this procedure.
Consider, for example, a library that contains the following two functions
function firstfunction(x::Float64)
return 2*x
end
function secondfunction(x::Float64)
return x^2
end
I would also like to implement multiple dispatch methods that can apply these functional forms to an vector of values, or an array of vectors (matrix). I could do this as follows
function firstfunction(x::Float64)
return 2*x
end
function firstfunction(xs::Vector{Float64})
f = similar(xs)
for i = 1:size(xs, 1)
f[i] = 2*xs[i]
end
return f
end
function firstfunction(xss::Matrix{Float64})
f = similar(xss)
for i = 1:size(xss, 1)
for j = 1:size(xss, 2)
f[i, j] = 2*xss[i, j]
end
return f
end
function secondfunction(x::Float64)
return x^2
end
function secondfunction(xs::Vector{Float64})
f = similar(xs)
for i = 1:size(xs, 1)
f[i] = xs[i]^2
end
return f
end
function secondfunction(xss::Matrix{Float64})
f = similar(xss)
for i = 1:size(xss, 1)
for j = 1:size(xss, 2)
f[i, j] = xss[i, j]^2
end
return f
end
But since all three versions of the function use the same kernel, and the actions of the various dispatches are the same across all functional forms, I'd like to know if there's a more efficient way to write this such that defining a new function for the library (e.g thirdfunction
) only involves explicitly writing the kernel function, rather than having to type out 2*n
essentially identical functions for n
functional forms in the library.
Just do:
This is the beauty of multiple-dispatch in Julia:
Note that however in your case it might make sense to have only a single representation of a function and let the user decide to vectorize it using the dot operator (
.
).And now the user just needs to add a dot when needed:
Since vectorizing in Julia is so easy you should consider this design whenever possible,