Hi everyone!
I’m looking for feedback on the approach of some code I’ve written. Since the code is for work I’ll share a greatly simplified version of what it looks like.
I’d like to hear opinions on the “right way” to store an eval
ed function in a struct
.
I’m not sure where I would need to be careful for performance pitfalls (Does the F<:Function
take care of everything? Do I need FunctionWrappers
?), or if there are more elegant ways to do this.
mutable struct S{T, F<:Function}
c::T
func::F
end
function S(config)
exprs = get_exprs(config)
# Running get_exprs takes a long time which is why I
# don't want this part in the cost function itself
fn = quote
function (s, x)
$(exprs...) # calculate a and b
# I don't know which values will be fixed, which values taken
# from x and which values calculated from those. So depending
# on the config it might evaluate a and b, maybe a and c,
# maybe only b... For example
a = x[1]
c = s.c
b = a^2 + c
d = x[2]
return cost(a, b, c, d)
end
end
s = S(config.c, eval(fn))
return s
end
function (s::S)(x)
s.func(s, x)
end
s = S(config)
optimize(x -> s(x))
Does this code look okay? What would be the fastest/most idiomatic/simply-the-best way to do this? If there are completely different approaches I’d be happy to hear them, too.