What is the best/most elegant code design in the Julia programming language for the following problem:
The modules mod1
, mod2
, mod3
, ... implement a complicated function fun(a,b,c)
, which calculates and returns a matrix M
.
A function foo
of my program needs to calculate the matrix M
repeatably via the function fun
with varying input parameters a,b,c
. However, the user of my program can specify which module is used for fun
. Note, that the user is no programmer and only wants to type something like julia program.jl
and specifies the used module with a string like "MODULE = mod2" in some input file.
The most naive and inelegant solution would probably be via if...elseif...
function foo(...
[...]
if SpecifiedModule == "mod1"
M = mod1.fun(a,b,c)
elseif SpecifiedModule == "mod2"
M = mod2.fun(a,b,c)
SpecifiedModule == "mod3"
M = mod3.fun(a,b,c)
end
# process M
An alternative way would be to use function-pointers. Or even functors
as known from C++?
What is best practice in Julia for this case? Is there a way to get rid of this ugly if..elseif... code?
PS: there are similarities to the case of finding an optimized value of a function, like in the module Optim.jl (https://github.com/JuliaNLSolvers/Optim.jl/). If I am not wrong, a user specified function f
is passed as an argument to the optimize(f, ...)
function.
Aucun commentaire:
Enregistrer un commentaire