I have some code that takes a function and uses the function to do some complicated computation. Thus, I wish to store this so I don't have to repeat this. Below, it is more simple than my real problem, but my code here has the same issue:
memoizedFunc[x_, fun_] := memoizedFunc[x, fun] = Module[{},
(* Use fun to do some complicated computation. *)
fun[x^2]
];
Do[
out = memoizedFunc[x, Cos[i*#] &];
Print[out]
, {i, 5}]
I expect the output to be {Cos[x^2, Cos[2 x^2], ... }
but that is not what happens. Without the memoization, I get the expected output. Somehow, Cos[i*#] & is interpreted as a function before the actual value of $i$ is substituted.
Even the following does not work, even tough the function used each time is different:
Do[
Clear[func];
func[k_] := Cos[i*k];
out = memoizedFunc[x, func];
Print[out]
, {i, 5}]
How do I fix this?
In my example, $x$ is just a symbol that appears in the output (variable name), so bonus points if memoizedFunc[x, func] stores the computation so that memoizedFunc[y, func] is basically the output of the first, but x substituted with y.
Do[With[{i = i},...– Kuba Oct 31 '15 at 12:33