# Replace the output of a module containing local variables by their actual value

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?

• Function has the attribute "HoldAll". That is why i is not replaced by its value. You can force the replacement by writing: With[{i = i}, Function[x, x + i]] instead of: Function[x, x + i] – Daniel Huber Dec 19 '20 at 19:29
• Is that "good practice" ? the syntax coloring gets all red. – julian haddad Dec 21 '20 at 2:44
• @julianhaddad I think it's fairly standard. If you don't like the coloring, you can always rename the inner variable to something else, e.g. With[{j=i},Function[x,x+j]] – Lukas Lang Dec 24 '20 at 9:18