0
$\begingroup$

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?

$\endgroup$
3
  • 2
    $\begingroup$ 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] $\endgroup$ – Daniel Huber Dec 19 '20 at 19:29
  • $\begingroup$ Is that "good practice" ? the syntax coloring gets all red. $\endgroup$ – julian haddad Dec 21 '20 at 2:44
  • $\begingroup$ @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]] $\endgroup$ – Lukas Lang Dec 24 '20 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.