I want to add (reduce?) anonymous functions and I can’t figure out how to do it.
Context: I want to speed up my computation like this:
function g(c, x) return hard_computation(c)(x) end
function gen_f(c) solution = hard_computation(c) return x -> solution(x) end f = gen_f(5)
f is much faster than
g because the result of the
hard_computation is cached inside
f (I assume).
hard_computation returns not a single but a bunch of functions and I’d like to combine them into one, for example, if my
hard_computation returns just a
cos with frequency and amplitude, I want to turn turn
x -> 1 * cos(1*x) x -> 2 * cos(2*x) x -> 3 * cos(3*x)
x -> 1 * cos(1*x) + 2 * cos(2*x) + 3 * cos(3*x)
So let’s say I have a
Array which I’m iterating over to get the function parameters:
function g(c, x) r = 0.0 for (a, b) in c r += a * cos(b * x) end return r end function gen_f(c) f = 0.0 for (a, b) in c f += x -> a * cos(b * x) # well this won't work, obviously... end return x -> f(x) end
Doing it the
function g-way is easy, just calculate each result and add them. However, that way I have to perform the “hard computation” every time I run the function, which I would like to avoid.
How do I do this the
If anyone has any other comments or tips on this kind of writing programs, I would love to hear them, as this is fairly new to me.