MathGroup Archive 1999

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

Search the Archive

Re: implementing a stack

  • To: mathgroup at
  • Subject: [mg16000] Re: [mg15922] implementing a stack
  • From: BobHanlon at
  • Date: Fri, 19 Feb 1999 03:27:12 -0500
  • Sender: owner-wri-mathgroup at

In a message dated 2/18/99 5:44:21 AM, wself at writes:

>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?
>push[a, 1] should push the number 1 onto the stack a, and
>return nothing,
>pop[a] should return whatever is on the top of stack a, and
>reset a to be the rest of the stack.


try this:

Clear[push, pop];
SetAttributes[{push, pop}, HoldFirst]
push[theStack_, elem_] := (theStack = {elem};) /; Length[theStack] == 0;
push[theStack_, elem_] := (theStack = Prepend[theStack, elem];);
pop[theStack_] := Null /; Length[theStack] == 0;
pop[theStack_] := Module[{frst = First[theStack]},
	theStack = Rest[theStack]; frst];

Bob Hanlon

  • Prev by Date: Re: Working in Modules
  • Next by Date: Re: Pure Functions in rules
  • Previous by thread: Re: implementing a stack
  • Next by thread: Re: implementing a stack