Currently I have a structure where I save functions into something of the sort
struct fooS
x::Float64
A::Dict{Symbol, Function}
fooS(x) = new(consfoo(x)...)
end
function consfoo(x)
return x, Dict{Symbol, Function}()
end
function fillDictionary(X, y, key)
p1 = y*X.x + 1
p2 = y*X.x^2 + 2
X.A[key] = u -> p1*u + p2
end
X = fooS(0.1)
fillDictionary(X, 0.2, :a)
function foo(X, x)
return X.A[:a](x)
end
@code_warntype foo(X, 0.1)
However this code is type unstable.
Would it be better to save the parameters generated in fillDictionary or wrap the function in something like function wrapper?
It’s hard to say what is “better” without knowing what your end application is. Why are you saving a dictionary of functions in the first place?
1 Like
The long story is that I have a struct, name Curve
Sometimes for a Curve I’m gonna need interpolators that I can compute from this data. There are 5 interpolators that I need to do this.
Since not every curve will need the interpolator, when I construct the struct I do not fill the array. But later when I have decided if I want to compute the interpolators I have to fill this dictionary.
So I use a dictionary because its mutable and its more clear which interpolator I’m calling this way
The short story is, it’s hard to store different functions in a single object and have it be type stable, because each function f
has its own specific type typeof(f)
. The two easiest solutions I see are
1 Like
Why not store the raw curve and the interpolator in different types, then?
e.g. have Curve
for the raw data with no interpolator. Then if you want to interpolate, wrap it in an InterpolatedCurve(curve)
that augments it with the interpolation data. If you have several different interpolation algorithms, you can have several InterpolatedCurve
types corresponding to different algorithms, or you can have a single type InterpolatedCurve{algorithm}
parameterized on the algorithm.
Basically, if your Curve
type may or may not contain other data, and that other data is not even type-stable, that’s a strong indication that you probably want to refactor your data structures.
2 Likes