I want to construct a function as the output of a Module, but I obtain the local variables as part of the output. This is a problem when I try to construct many of these functions in a parallel table, because all these local variables appear to die when the parallel computations end.
Minimal example:
If I write
Module[{i = RandomInteger[{0, 100}]},
Function[x, x + i]
]
I obtain
Function[x$, x$ + i$197286]
Now the problem:
If I write
t = ParallelTable[
Module[{i = RandomInteger[{0, 100}]},
Function[x, x + i]
],
4
];
Through[t[5]]
I obtain
{5 + i$19726, 5 + i$21792, 5 + i$20597, 5 + i$19520}
and the variables like i$19724
have no value.
If I use Table instead of ParallelTable I get what I want
{60, 13, 62, 13}
I found a workaround by doing
Module[{i = RandomInteger[{0, 100}]},
With[{ei = i}, Function[x, x + ei]]
]
obtaining
Function[x$, x$ + 15]
which is EXACTLY what I want. I prefer to have concrete values inside the functions, even if I don't use parallelization.
But I have to introduce a new variable. And this is a problem if there are many of these constants inside the function. Is there a way to solve this problem without using a new variable?
With[{j=i},Function[x,x+j]]
$\endgroup$ – Lukas Lang Dec 24 '20 at 9:18