I’m writing a Monte Carlo program and I need a lot of auxiliary function dependent on one or two fields of the parameter model of the main function sweep!(model) in the following way:
function sweep!(model, n_sweep)
α = some_expression_of_parameters_in(model)
β = some_other_expression_of_parameters_in(model)
# ...
# α, β, ... don't change in the following code
#...
for _ in 1 : n_sweep
my_auxiliary_function() # The definition of the function is dependent on α, β, ...
end
end
The auxiliary functions are called in each loop of sweeping, so I want them to be as fast as possible. Currently I define them in sweep!, so that α, β, … aren’t passed through the parameters of my_auxiliary_function. This is not very readable (causing sweep! to be a 300-line function), so I want to define my_auxiliary_function outside.
But here comes the problem of how to pass α, β, … to my_auxiliary_function. I will frequently change the number and definition of these quantities, and my_auxiliary_function appears in multiple places, so if I just define my_auxiliary_function as my_auxiliary_function(α, β, ..., other_parameters), whenever I change the number and definition of α, β, …, I need to change all my_auxiliary_function. Besides, since α, β, … never change after they are calculated, this kind of calling convention is rather distracting.
I can also build a struct to contain α, β, …, and pack these values into one struct, and pass the struct to my_auxiliary_function. But unpacking a struct takes time.
What should I do, then, to move my_auxiliary_function out of sweep!?