Re: MyPrependTo
- To: mathgroup at smc.vnet.net
- Subject: [mg15966] Re: MyPrependTo
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Fri, 19 Feb 1999 03:26:54 -0500
- References: <7ag26u$ag9@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Will Self wrote in message <7ag26u$ag9 at smc.vnet.net>... > >In trying to create my own version of PrependTo, I ran into some strange >stuff that I don't understand. I am calling my function "push". Please >look at the session below and explain these mysterious happenings. >It seems clear that there is more than one symbol e kicking around, >but I can't make head or tail of it. See also my next message for >the larger context. > > >In[2]:= >push[someStack_, elt_] := (someStack = Prepend[someStack, elt];) > >In[3]:= >e=stack["expression"] >Out[3]= >stack["expression"] > >In[4]:= >push[e,1] > >In[5]:= >e >Out[5]= >stack[1,"expression"] > >In[6]:= >push[e,2] > >In[7]:= >e > >Out[7]= >stack[2,1,"expression"] > >In[8]:= >Rest[e] >Out[8]= >stack[2,1,"expression"] (* WHAT!!!!???? *) > >In[9]:= >?e >"Global`e" >e = stack["expression"] (* DOUBLE WHAT!!!!???? *) > > >Will Self > Will EXPLANATION With >push[someStack_, elt_] := (someStack = Prepend[someStack, elt]; push[s,e] causes the evaluation of value[s] = Prepend[s,e] not the evaluation of s = Prepend[s,e] So, after >s=stack[e] >push[e,1] simply adds the assignment stack[e] = stack[1,e] so that we now have stored s = stack[e] and stack[e] = stack[1,e] (nowhere is e = stack[1,e] stored; the current value of e has to be constructed from the two preceding definitions: e -> stack[e] ->stack[1,e]) Now: Rest[e] evauates as follows Rest[e] -> Rest[stack[e]] -> Rest[stack[1,e]] -> stack[e] -> stack[1,e] The last step is the surprise! SOLUTION SetAttributes[push, HoldFirst] Note: When ?e is entered it gives the value of e by using the current stored definitions: this does not reveal the mechanism above. Using FullDefinition[e] will reveal all. Allan --------------------- Allan Hayes Mathematica Training and Consulting Leicester UK www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565