Re: implementing a stack
- To: mathgroup at smc.vnet.net
- Subject: [mg16015] Re: [mg15922] implementing a stack
- From: Clemens Frey <btml01 at uni-bayreuth.de>
- Date: Sat, 20 Feb 1999 02:52:05 -0500
- Sender: owner-wri-mathgroup at wolfram.com
Hi Will!
Although Bob has already posted a solution, here is mine. I strongly use
the Hold-Attribute to keep the function arguments from being evaluated.
But as I want to implement a little own data type, I want to test if the
right stuff is being given to the push/pop functions, so I have to use a
conditioned pattern together with a ReleaseHold just to evaluate the
argument when I want. Be careful to define the pop fct exactly in the
given order, since Mathematica cannot decide which condition is more specific
here. The first pop-rule just returns Null if an empty stack is given to
it. Instead of the very inefficient Prepend-fct I use a Flatten-construct.
init := TStack[];
SetAttributes[push,HoldFirst];
push[ s_Symbol/;Head[ReleaseHold[s]]==TStack, elem_ ] :=
(s = Flatten[TStack[elem,s]];)
SetAttributes[pop,HoldAll];
pop[ s_Symbol /;ReleaseHold[s]==TStack[] ] = Null;
pop[ s_Symbol /;Head[ReleaseHold[s]]==TStack ] :=
{First[s],s = Rest[s]} [[1]]
Now you can use these definitions:
s = init;
push[s,2]
push[s,xx]
pop[s]
xx
pop[s]
2
pop[s] //FullForm
Null
Bye
Clemens
------------------------------------------------------------
Clemens Frey
Doctoral Student at the
Department of Mathematics/BITOEK
University of Bayreuth(Germany)
clemens.frey at uni-bayreuth.de
http://www.bitoek.uni-bayreuth.de/~Clemens.Frey
------------------------------------------------------------
On Wed, 17 Feb 1999, Will Self wrote:
> I would like to implement a simple stack in Mathematica.
> I can use PrependTo for "push", but in that case how do
> I implement "pop"? I have thought about this and I see
> that I can do it by creating a global variable that keeps
> a list of pairs: the symbols that serve as the names
> of the stacks, and the stacks themselves; and having pop
> and push access and manipulate this list. Is that really
> what I have to do?
>
> Explicitly,
> push[a, 1] should push the number 1 onto the stack a, and
> return nothing,
> and
> pop[a] should return whatever is on the top of stack a, and
> reset a to be the rest of the stack.
>
> Will Self
>