I have a certain list of functions fs
and coefficients cs
with which I would like form a linear combination, e.g., I’d like to obtain the function
(args...; kwargs...) -> ( cs[1] * f[1](args...; kwargs...) + ...
+ cs[n] * f[n](args...; kwargs...) )
The attempt
function linear_combination(fs, coeffs)
(args...; kwargs...) -> sum(c * f(args...; kwargs...) for (c,f) ∈ zip(coeffs, fs))
end
is a partial solution. By runing the example
f(x) = x
g(x) = x^2
fs = (f, g)
coeffs = (1,1/2)
h = linear_combination(fs, coeffs)
h(1) # 1.5
I get the expected answer, but running @code_warntype h(1)
gives me
MethodInstance for (::var"#15#18"{var"#15#16#19"{Tuple{typeof(f), typeof(g)}, Tuple{Int64, Float64}}})(::Int64)
from (::var"#15#18")(args...; kwargs...) @ Main ~/Desktop/DevStructuredLight.jl/test.jl:4
Arguments
#self#::var"#15#18"{var"#15#16#19"{Tuple{typeof(f), typeof(g)}, Tuple{Int64, Float64}}}
args::Tuple{Int64}
Body::Any
1 ─ %1 = Core.getfield(#self#, Symbol("#15#16"))::var"#15#16#19"{Tuple{typeof(f), typeof(g)}, Tuple{Int64, Float64}}
│ %2 = Core.NamedTuple()::Core.Const(NamedTuple())
│ %3 = Base.pairs(%2)::Core.Const(Base.Pairs{Symbol, Union{}, Tuple{}, @NamedTuple{}}())
│ %4 = Core.tuple(%3, #self#)::Tuple{Base.Pairs{Symbol, Union{}, Tuple{}, @NamedTuple{}}, var"#15#18"{var"#15#16#19"{Tuple{typeof(f), typeof(g)}, Tuple{Int64, Float64}}}}
│ %5 = Core._apply_iterate(Base.iterate, %1, %4, args)::Any
└── return %5
so h
is not type stable. Could anyone help me improve this solution? Thanks!