Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1999

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

Search the Archive

Re: implementing a stack

  • To: mathgroup at
  • Subject: [mg16015] Re: [mg15922] implementing a stack
  • From: Clemens Frey <btml01 at>
  • Date: Sat, 20 Feb 1999 02:52:05 -0500
  • Sender: owner-wri-mathgroup at

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[];

push[ s_Symbol/;Head[ReleaseHold[s]]==TStack, elem_ ] := 
	(s = Flatten[TStack[elem,s]];)

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;





pop[s] //FullForm


Clemens Frey
Doctoral Student at the 
Department of Mathematics/BITOEK
University of Bayreuth(Germany)

clemens.frey at

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

  • Prev by Date: Q: Union and SameTest Option
  • Next by Date: Re: Pure Functions in rules
  • Previous by thread: Re: implementing a stack
  • Next by thread: Re: implementing a stack