8

I have a question about FullDefinition and how it interacts with the local variables of Module.

I've created a few functions (with Module) and I wanted to save their definitions, so I can use them later. These functions call other functions and so I wanted to use Save to have their FullDefinition saved.

The problem I have is that when I do this, it also saves whatever variable which happened to have the same name of that one of the local Module[] variable.

A simple example would be :

g[t_] := 5*t;
f[t_] := Module[{c},
  c = g[t];
  Return[c]
  ]

I use another variable :

c = 2;

and now if I call FullDefinition[] :

FullDefinition[f]
(*
    f[t_] := Module[{c}, c = g[t]; Return[c]]
    c = 2
    g[t_] := 5 t   *)

I don't really understand why FullDefinition contains the global assignment of c, and it's really a problem if I don't want global variables to pollute my saved file. I don't want them to be loaded every time I load the functions.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
user7987
  • 295
  • 1
  • 6
  • 2
    Since the local variable c in the module will be aliased to something like c$2546 when the definition of f is evaluated, this looks like a bug in FullDefition to me. As an aside, the Return[c] in your definition of f is unnecessary because Module returns the last expression it evaluates, and good practice dictates that Return not be used when it isn't needed. – m_goldberg Jun 11 '13 at 01:26
  • By looking at the details and all examples in the help document, the possible reason is that FullDefinition[expr] just PRINTs all the symbols relative to expr, not distinguishing Local variables from global ones, because of its attribute of HoldAll. – Z-Y.L Jun 11 '13 at 01:28

1 Answers1

6

I suspect the problem here is, that FullDefinition only looks at the DownValues but doesn't evaluate the expressions so that the localization (in the case of Module lexical scoping) is not performed. Although your example is sufficient, looking at the following reveals that FullDefinition can give completely wrong results:

f[x_] := x^2;
g[x_] := Module[{f},
  f[y_] := 2 y;
  x + f[x]
]

As you see the f inside module is defined as 2y but when you now look at the output of FullDefinition you see

FullDefinition[g]
(*
g[x_]:=Module[{f},f[y_]:=2 y;x+f[x]]
f[x_]:=x^2
*)

which is completely wrong. Therefore, you cannot rely on FullDefinition for your purpose and as solution I see currently nothing else than implementing something yourself.

One of the first places to start for such an implementation is the Automatically generating a dependency graph of an arbitrary Mathematica function? discussion.

halirutan
  • 112,764
  • 7
  • 263
  • 474