Re: MyPrependTo
- To: mathgroup at smc.vnet.net
- Subject: [mg15998] Re: [mg15921] MyPrependTo
- From: David Withoff <withoff>
- Date: Fri, 19 Feb 1999 03:27:11 -0500
- Sender: owner-wri-mathgroup at wolfram.com
> 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 Your push function is an assignment function, and like all assignment functions (in any programming language) must hold the assignment target unevaluated in order to work. If you use inputs such as In[3]:= push[Unevaluated[e], 1] or if you set the HoldFirst attribute for push, this function will do what I believe you had expected. There is only one symbol e kicking around. In your example, push[e,1] doesn't modify e. It modifies the expression that results when e is evaluated, which is an expression with a head of stack, so push[e,1] assigns a value to stack. Your ?e evaluation shows that e is unchanged. If you evaluate ?stack, you will see the rules for stack. Rest[e] returns your "WHAT!!!!????" result because of the rules for stack. There is a rule for stack[1,"expression"] that causes it to evaluate to stack[2,1,"expression"]. Rest[stack[2,1,"expression"]] returns stack[1,"expression"] as an intermediate result, and that result evaluates to stack[2,1,"expression"]. Dave