2
$\begingroup$

In the code below, I define and plot a local function f.

Clear[f]
Module[{f}, f[x_] := 1; Plot[f[x], {x, 0, 1}]]

However, after evaluation, ?f reveals that the definition of f has become global. Why is this so?

$\endgroup$
2
  • $\begingroup$ Welcome to Mathematica.SE! I suggest that: 1) You take the introductory Tour now! 2) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! 3) As you receive help, try to give it too, by answering questions in your area of expertise. $\endgroup$
    – bbgodfrey
    Feb 3 '15 at 11:51
  • $\begingroup$ anon, welcome. Your question has been asked and answered before. Please see the link in the banner inserted at the top of your post. $\endgroup$
    – Mr.Wizard
    Feb 3 '15 at 14:54
1
$\begingroup$

Nasser is correct that the symbol name f appears to have leaked out of Module. However, I believe that this causes no harm, because it actually is a distinct symbol from that in the Module:

ClearAll["Global`*"]; Remove["Global`*"];

(* Remove::rmnsm: There are no symbols matching "Global`*". >> *)

Module[{f}, f[x_] := 1; {Information[f], Plot[f[x], {x, 0, 1}]}]

(* Global`f$1433
      Attributes[f$1433]={Temporary} 
  f$1433[x_]:=1
followed by the plot *)

Information[f]

(* Global`f *)
$\endgroup$
4
  • $\begingroup$ Are you sure about this? How about this: ClearAll["Global*"] Remove["Global*"]; Module[{f = 0}, 0]; and now type ?f you'll see it in the global symbol table. How can this be explained? Since f now is just symbol inside a Module? but notice only the symbol is leaked. It has no value in Global, only its name is entered. $\endgroup$
    – Nasser
    Feb 3 '15 at 12:03
  • $\begingroup$ @Nasser I see your point. Certainly, there are two different fs, but, perhaps, I am answering the wrong question. I need to think about this. Thanks. $\endgroup$
    – bbgodfrey
    Feb 3 '15 at 12:13
  • $\begingroup$ @Nasser Thanks. This is more subtle than I had supposed. $\endgroup$
    – bbgodfrey
    Feb 3 '15 at 12:31
  • $\begingroup$ @Nasser and bbgodfrey, the Global`f is created during parsing. See my answer to the marked duplicate for reference. $\endgroup$
    – Mr.Wizard
    Feb 3 '15 at 14:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.