I’m building a simulation framework and am running into the following problem:
I have a initialisation function init_model(x::InitType) where x is a structure containing the information needed for initialisation of a model. In the init function I define an anonymous function that uses some data from x. What data is used and how many fields are used is dependant on the specific InitType.
When I use a regular anonymous function I get a huge performance hit, which is apparently due to the fact that the anonymous function is not a const by default. However, I can not use the const keyword in a function. How would I solve this in an elegant way without loosing the flexibility of the simulation framework.
Here’s the (simplified) code:
struct Model
sim_function::Function
end
function run_simulation(model::Model, steps::Int)
for i in 1:steps
model.sim_function(i)
end
end
abstract type Init end
struct InitType <: Init
increment::Int
end
function increment_sim(x::Int, increment::Int)
return x + increment
end
function init_model(init::InitType)
# This does not compile. This is the problem.
# It compiles without the const keyword but then performance goes out the window.
const sim_function = x -> increment_sim(x, init.increment)
return Model(sim_function)
end
init = InitType(2)
run_simulation(init_model(init), 3)
EDIT: I don’t really understand why the const keyword is not allowed in a local context since it is perfectly possible to define a named function in the local scope of another function and since all named functions are const by default I’m guessing this should also be possible for anonymous functions?