Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1999
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*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 smc.vnet.net
  • Subject: [mg16000] Re: [mg15922] implementing a stack
  • From: BobHanlon at aol.com
  • Date: Fri, 19 Feb 1999 03:27:12 -0500
  • Sender: owner-wri-mathgroup at wolfram.com

In a message dated 2/18/99 5:44:21 AM, wself at viking.emcmt.edu 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?
>
>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,

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