MathGroup Archive 2008

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

Search the Archive

Re: When is a List not a List?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg90958] Re: When is a List not a List?
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Thu, 31 Jul 2008 06:04:38 -0400 (EDT)
  • Organization: The Open University, Milton Keynes, UK
  • References: <g6rntk$7kj$1@smc.vnet.net>

AES wrote:

>    g[x_, n_] := x^n
>    FullForm[Table[g[x, n], {n, 1, 2}]]
>    FullForm[{g[x, 1], g[x, 2]}]
>    Plot[{g[x, 1], g[x, 2]}, {x, 0, 1}, PlotStyle -> {Red, Blue}]
>    Plot[Table[g[x, n], {n, 1, 2}], {x, 0, 1}, PlotStyle -> {Red, Blue}]
> 
> The FullForm[]s are identical.  One Plot[] has red and blue curves; the 
> other has two blue curves.
> 
> Quirky!

Not at all, as it has already been explained many times in this very 
newsgroup (notwithstanding the online help that contains some examples 
illustrating this point).

Plot does not evaluate immediately its arguments because it has the 
attribute HoldAll:

     Attributes[Plot]

     {HoldAll, Protected}

So, having the attribute HoldHold, what Plot "sees" in first instance 
the unevaluated expression Table[g[x, n], {n, 1, 2}], which stands for 
only *one* function. Thus the choice of colors is just for one 
function/expression, not for the list of functions that will be returned 
after evaluation of the first argument.

To force the evaluation of the first argument before doing anything 
else, one must use Evaluate, so Mathematica's main loop evaluates 
Table[g[x, n], {n, 1, 2}] to the list {g[x, 1], g[x, 2]} and feed Plot 
with this list as first argument. Then Plot is evaluated and "sees" a 
list of two function as its first argument and thus select two colors.

As usual, Trace might be useful to have a glimpse at what's going on.

   Plot[Table[g[x, n], {n, 1, 2}], {x, 0, 1},
     PlotStyle -> {Red, Blue}] // Trace

     {Plot[Table[g[x,n],{n,1,2}],{x,0,1},PlotStyle->{Red,Blue}],
     {x=.,Null},{x=.,Null},{{x}=.,{x=.},{x=.,Null},{Null}},
     {Table[g[x,n],{n,1,2}],{{x,0.0000204286},{n,1},
     g[0.0000204286,1],0.0000204286^1,0.0000204286},
     [...]

   Plot[Evaluate@Table[g[x, n], {n, 1, 2}], {x, 0, 1},
     PlotStyle -> {Red, Blue}] // Trace

     {{Table[g[x,n],{n,1,2}],{{n,1},g[x,1],x^1,x},
     {{n,2},g[x,2],x^2},{x,x^2}},
     Plot[{x,x^2},{x,0,1},PlotStyle->{Red,Blue}],
     [...]

Regards,
-- Jean-Marc



  • Prev by Date: Re: Problem with evaluating Graphics3D output
  • Next by Date: Re: NMaximize Questions
  • Previous by thread: Re: When is a List not a List?
  • Next by thread: Performance of Array Addition