Mathematica 9 is now available
Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: understanding code

  • To: mathgroup at smc.vnet.net
  • Subject: [mg114219] Re: understanding code
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Sat, 27 Nov 2010 03:38:21 -0500 (EST)

Hi Bill,

PreIncrement must have been implemented on the higher level, using Set,
which
can be illustrated as follows:

In[12]:=
i[1]=0
Out[12]= 0

In[13]:= On[Set]
In[14]:= i[1]++

During evaluation of In[14]:= Set::trace: i[1]=1 --> 1. >>
Out[14]= 0
In[15]:= Off[Set]

I would not be surprised in the implementation looks something like this:

SetAttributes[preIncrement, HoldFirst];
preIncrement[expr_]:=
    With[{value = expr},  expr=value+1;value];


In any case, there seem to be no additional restrictions imposed by
PreIncrement
on an expression being incremented, as compared to those of Set (that it
must be an
L - value). Particularly, indexed variables like i[1] are ok.

Regards,
Leonid



On Fri, Nov 26, 2010 at 1:26 PM, Bill Rowe <readnews at sbcglobal.net> wrote:

> On 11/25/10 at 5:57 AM, sam.takoy at yahoo.com (Sam Takoy) wrote:
>
> >The following code:
>
> >i[_] = 0;
> >i[1]++
> >i[1]++
> >i[1]++
> >i[1]++
>
> >return 0 1 2 3 4. I'd like to understand whats going on here. That
> >is,
>
> >What is i?  Is it a function? And what is i[1]? Is it a function or
> >a value? Etc...
>
> It is a function. i[1] is the function i evaluated at i. You can
> see what is going on by using Trace, i.e.,
>
> In[3]:= Trace[i[1]++]
>
> Out[3]= {i(1)++,{i(1),0},{i(1)=1,1},0}
>
> As you can see, i[1] gets evaluated to whatever value it had
> previously which initially is zero. Then the result gets
> incremented by 1 and is then assigned to be the new value for
> i[1]. This last step is not something I would have expected
> without your example and I don't know why it occurs.
>
> I can see times where this behavior might be useful. For
> example, it is at times convenient to see i[1] as a subscripted
> variable. Thinking of i[1] this way, the notation i[1]++ would
> be interpreted as incrementing the subscripted variable by one
> and the Mathematica behavior is consistent with this.
>
>
>


  • Prev by Date: Re: Rendering transparent objects changed in M8
  • Next by Date: Re: Compile and arrays
  • Previous by thread: Re: understanding code
  • Next by thread: Efficient search for bounding list elements