... until the collector arrives ...

This "blog" is really just a scratchpad of mine. There is not much of general interest here. Most of the content is scribbled down "live" as I discover things I want to remember. I rarely go back to correct mistakes in older entries. You have been warned :)


Mathematica Pure Function Scope Problem

Consider this snippet:

f[x_] := g[Function[a, x]];
g[fn_] := Module[{h}, h[a_] := fn[a]; h[0]];

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)


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]];

=> 999

Another workaround is to compile the function:

f[x_] := g[Compile[a, x]];

=> 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.

Blog Archive