Per comments, including here the description of the problem lifted from another site:
Mathematica Pure Function Scope Problem
Consider this snippet:
f[x_] := g[Function[a, x]]; g[fn_] := Module[{h}, h[a_] := fn[a]; h[0]]; f[999]
Executing this sequence generates errors messages:
Function::flpar: Parameter specification {0} in Function[{0},999] should be a symbol or a list of symbols. (x3) $RecursionLimit::reclim: Recursion depth of 256 exceeded. (x4) Hold[Function[{0},999][0]]
However, if you change the name of the function variable in the first line from a to z, then all works as expected:
f[x_] := g[Function[z, x]]; f[999] => 999
Another workaround is to compile the function:
f[x_] := g[Compile[a, x]]; f[999] => 999
The problem appears to be caused by a name conflict between the pure function's argument a and the helper function h's argument a. This is a really nasty problem because the definitions are completely separate -- one would have to perform a global code analysis to turn up such problems.
I'm a relatively new user of Mathematica
and have already ran into that problem, asked and answered here.
I'm used to C++
; in C++
and most other programming languages) local scope of function arguments and local scope of most variables prevents variable name clash between different functions.
Thus the question: how does one prevent the above problem in Mathematica
?
f[999] // Trace // Quiet
makes clear what's going on, I think, for those who can readTrace
output. Botha
are renamed to prevent clashes, but renamed to the same thinga$
, which causes the clash. Bummer. This language area is not my forte, but it looks like a bug. $\endgroup$