MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Scoping question

  • To: mathgroup at
  • Subject: [mg85713] Re: Scoping question
  • From: Szabolcs Horvát <szhorvat at>
  • Date: Wed, 20 Feb 2008 06:50:33 -0500 (EST)
  • Organization: University of Bergen
  • References: <fpdv0k$ref$>

Yaroslav Bulatov wrote:
> The code below defines a function with parameter x. The body contains
> another function definition which uses this parameter. Why do "inner x
> is" and "outer x is" lines start reporting different values at one
> point?
> f1[x_] := (
>   f2[y_] := (Print["inner x is ", x]; If[x + 1 < 3, f1[x + 1], 1]);
>   (Print["outer x is ", x]; f2[#]) & /@ Range[2];
>   )
> f1[1]

Hi Yaroslav,

Scoping in Mathematica is slippery terrain, but this is not about 
scoping.  If you step through your functions manually, you will 
understand what happens.

Here is a rewritten, cleaner version of the same algorithm.  (This could 
be directly translated to a static language like C.) Perhaps this will 
make things clear:

(* 'global' is a global variable *)

fun2 :=
  (Print["fun2: ", global];
   If[global <= 1,
    fun1[global + 1]

fun1[arg_] :=
  (global = arg;
   Print["fun1: ", arg]; fun2;
   Print["fun1: ", arg]; fun2;)

When the last "inner x" is printed, the global variable (i.e. f2 in your 
version) is already redefined to have the value 2.  The outermost f1 
(i.e. outermost in the recursion) is not changing it back to 1, so it 
remains 2.  But f1 does not print 'global'.  It prints the argument that 
was passed to it.  Therefore the last "outer x" is 1, not 2.

I hope this helps,

  • Prev by Date: Re: Default font
  • Next by Date: Re: Sterographic display
  • Previous by thread: Re: Scoping question
  • Next by thread: No "show labels for the edges" for GraphPlot3D