Stack: Difference between revisions

98,471 bytes added ,  2 months ago
m
(Added zkl)
(172 intermediate revisions by 76 users not shown)
Line 2:
[[Category:Encyclopedia]]
{{data structure}}[[Category:Classic CS problems and programs]]
A '''stack''' is a container of elements with last in, first out access policy. Sometimes it also called '''LIFO'''. The stack is accessed through its '''top'''. The basic stack operations are:
 
A '''stack''' is a container of elements with &nbsp; <big><u>l</u>ast <u>i</u>n, <u>f</u>irst <u>o</u>ut</big> &nbsp; access policy. &nbsp; Sometimes it also called '''LIFO'''.
* ''push'' stores a new element onto the stack top;
* ''pop'' returns the last pushed stack element, while removing it from the stack;
* ''empty'' tests if the stack contains no elements.
 
The stack is accessed through its '''top'''.
 
The basic stack operations are:
 
* &nbsp; ''push'' &nbsp; stores a new element onto the stack top;
* &nbsp; ''pop'' &nbsp; returns the last pushed stack element, while removing it from the stack;
* &nbsp; ''empty'' &nbsp; tests if the stack contains no elements.
 
<br>
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
 
* &nbsp; ''top'' &nbsp; (sometimes called ''peek'' to keep with the ''p'' theme) returns the topmost element without modifying the stack.
 
<br>
Stacks allow a very simple hardware implementation. They are common in almost all processors. In programming stacks are also very popular for their way ('''LIFO''') of resource management, usually memory. Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks). This is a classical way to implement local variables of a reentrant or recursive subprogram. Stacks are also used to describe a formal computational framework. See [[wp:Stack_automaton|stack machine]]. Many algorithms in pattern matching, compiler construction (e.g. [[wp:Recursive_descent|recursive descent parsers]]), and machine learning (e.g. based on [[wp:Tree_traversal|tree traversal]]) have a natural representation in terms of stacks.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way ('''LIFO''') of resource management, usually memory.
 
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
 
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
 
See [[wp:Stack_automaton|stack machine]].
 
Many algorithms in pattern matching, compiler construction (e.g. [[wp:Recursive_descent|recursive descent parsers]]), and machine learning (e.g. based on [[wp:Tree_traversal|tree traversal]]) have a natural representation in terms of stacks.
 
 
;Task:
Create a stack supporting the basic operations: push, pop, empty.
 
 
{{Template:See also lists}}
<br><br>
 
=={{header|11l}}==
{{trans|Crystal}}
 
<syntaxhighlight lang="11l">[Int] stack
 
L(i) 1..10
stack.append(i)
 
L 10
print(stack.pop())</syntaxhighlight>
 
{{out}}
<pre>
10
9
8
7
6
5
4
3
2
1
</pre>
=={{header|6502 Assembly}}==
The 6502 has a built-in stack, which is located at memory addresses $0100-$01FF. The first thing most boot ROMs will do is set the stack to equal $FF. Only the X register can interact with the stack pointer's value directly, and it does so using <code>TSX</code> (transfer stack to X) and <code>TXS</code> (transfer X to stack.) Each push will decrement S by 1 and write that byte to the stack memory. On the original 6502, only the accumulator could be pushed to the stack, so programs running on those CPUs would often use sequences such as <code>TXA PHA</code> and <code>TYA PHA</code> to save the X and Y registers. This had the nasty habit of destroying the accumulator, which made saving these registers difficult. Fortunately, the 65c02 and its later revisions can push/pop X and Y directly without having to go through the accumulator first.
 
Push:
<syntaxhighlight lang="6502asm">PHA</syntaxhighlight>
Pop:
<syntaxhighlight lang="6502asm">PLA</syntaxhighlight>
Empty:
<syntaxhighlight lang="6502asm">TSX
CPX $FF
BEQ stackEmpty</syntaxhighlight>
Peek:
<syntaxhighlight lang="6502asm">TSX
LDA $0101,x</syntaxhighlight>
 
=={{header|68000 Assembly}}==
The 68000 is well-suited to stack data structures. Register A7 contains the stack pointer, however any address register can be used for a similar purpose. Any register from A0-A6 can be pointed to work RAM and used as a stack.
 
===Push===
You can push the contents of one or more variables.
<syntaxhighlight lang="68000devpac">LEA userStack,A0 ;initialize the user stack, points to a memory address in user RAM. Only do this once!
MOVEM.L D0-D3,-(A0) ;moves the full 32 bits of registers D0,D1,D2,D3 into the address pointed by A0, with pre-decrement</syntaxhighlight>
 
Unlike the "true" stack (A7), you can push a single byte onto the user stack and it won't get automatically padded with a trailing null byte.
 
===Pop===
The pop is just a reverse push.
<syntaxhighlight lang="68000devpac">MOVEM.L (A0)+,D0-D3 ;returns the four longs stored in the stack back to where they came from.</syntaxhighlight>
 
===Empty===
The stack is empty if and only if the stack pointer equals its initialized value. This is only true provided you have never adjusted the stack pointer except by pushing and popping.
<syntaxhighlight lang="68000devpac">CMPA.L #userStack,A0
BEQ StackIsEmpty</syntaxhighlight>
 
===Manually adjusting the stack===
You can offset the user stack (and the real stack) as follows:
<syntaxhighlight lang="68000devpac">LEA (4,SP),SP ;does the same thing to the stack as popping 4 bytes, except those bytes are not retrieved.</syntaxhighlight>
 
===Peek===
If you know the intended length of the last item on the stack (1, 2, or 4 bytes), you can load it into memory without popping it. This applies to both the real stack and a user stack you may have created. Since this operation doesn't alter the value of the stack pointer, you don't have to worry about misaligning the stack, but the value you peek at should be of the correct size or you'll be "peeking" at more than one item at the same time.
 
<syntaxhighlight lang="68000devpac">MOVE.W (SP),D0 ;load the top two bytes of the stack into D0
MOVE.W (A0),D0 ;load the top two bytes of A0 into D0</syntaxhighlight>
 
=={{header|8086 Assembly}}==
The 8086's hardware stack is very similar to that of [[Z80 Assembly]]. This is no coincidence, as the Z80 was based on the predecessor to the 8086.
 
<syntaxhighlight lang="asm">push ax ;push ax onto the stack
pop ax ; pop the top two bytes of the stack into ax</syntaxhighlight>
 
The "high" byte is pushed first, then the low byte. Popping does the opposite.
 
Depending on your assembler, the stack's initial value may be set using the <code>.stack</code> directive.
 
Like the Z80, the 8086 can only push or pop 2 bytes at a time. It's not possible to push <code>AH</code> without pushing <code>AL</code> alongside it. The stack can be used to exchange values of registers that even the <code>XCHG</code> command can't work with. This is done by deliberately pushing two registers and popping them in the "wrong" order.
 
The easiest way to "peek" is to pop then push that same register again.
<syntaxhighlight lang="asm">;get the top item of the stack
pop ax
push ax</syntaxhighlight>
 
The stack need not be accessed using these push and pop commands, it can also be read like any other area of memory. This is actually how [[C]] programs store and recall local variables and function arguments.
 
 
=={{header|ABAP}}==
 
This works for ABAP Version 7.40 and above
 
<syntaxhighlight lang="abap">
report z_stack.
 
interface stack.
methods:
push
importing
new_element type any
returning
value(new_stack) type ref to stack,
 
pop
exporting
top_element type any
returning
value(new_stack) type ref to stack,
 
empty
returning
value(is_empty) type abap_bool,
 
peek
exporting
top_element type any,
 
get_size
returning
value(size) type int4,
 
stringify
returning
value(stringified_stack) type string.
endinterface.
 
 
class character_stack definition.
public section.
interfaces:
stack.
 
 
methods:
constructor
importing
characters type string optional.
 
 
private section.
data:
characters type string.
endclass.
 
 
class character_stack implementation.
method stack~push.
characters = |{ new_element }{ characters }|.
 
new_stack = me.
endmethod.
 
 
method stack~pop.
if not me->stack~empty( ).
top_element = me->characters(1).
 
me->characters = me->characters+1.
endif.
 
new_stack = me.
endmethod.
 
 
method stack~empty.
is_empty = xsdbool( strlen( me->characters ) eq 0 ).
endmethod.
 
 
method stack~peek.
check not me->stack~empty( ).
 
top_element = me->characters(1).
endmethod.
 
 
method stack~get_size.
size = strlen( me->characters ).
endmethod.
 
 
method stack~stringify.
stringified_stack = cond string(
when me->stack~empty( )
then `empty`
else me->characters ).
endmethod.
 
 
method constructor.
check characters is not initial.
 
me->characters = characters.
endmethod.
endclass.
 
 
class integer_stack definition.
public section.
interfaces:
stack.
 
 
methods:
constructor
importing
integers type int4_table optional.
 
 
private section.
data:
integers type int4_table.
endclass.
 
 
class integer_stack implementation.
method stack~push.
append new_element to me->integers.
 
new_stack = me.
endmethod.
 
 
method stack~pop.
if not me->stack~empty( ).
top_element = me->integers[ me->stack~get_size( ) ].
 
delete me->integers index me->stack~get_size( ).
endif.
 
new_stack = me.
endmethod.
 
 
method stack~empty.
is_empty = xsdbool( lines( me->integers ) eq 0 ).
endmethod.
 
 
method stack~peek.
check not me->stack~empty( ).
 
top_element = me->integers[ lines( me->integers ) ].
endmethod.
 
 
method stack~get_size.
size = lines( me->integers ).
endmethod.
 
 
method stack~stringify.
stringified_stack = cond string(
when me->stack~empty( )
then `empty`
else reduce string(
init stack = ``
for integer in me->integers
next stack = |{ integer }{ stack }| ) ).
endmethod.
 
 
method constructor.
check integers is not initial.
 
me->integers = integers.
endmethod.
endclass.
 
 
start-of-selection.
data:
stack1 type ref to stack,
stack2 type ref to stack,
stack3 type ref to stack,
 
top_character type char1,
top_integer type int4.
 
stack1 = new character_stack( ).
stack2 = new integer_stack( ).
stack3 = new integer_stack( ).
 
write: |Stack1 = { stack1->stringify( ) }|, /.
stack1->push( 'a' )->push( 'b' )->push( 'c' )->push( 'd' ).
write: |push a, push b, push c, push d -> Stack1 = { stack1->stringify( ) }|, /.
stack1->pop( )->pop( importing top_element = top_character ).
write: |pop, pop and return element -> { top_character }, Stack1 = { stack1->stringify( ) }|, /, /.
 
write: |Stack2 = { stack2->stringify( ) }|, /.
stack2->push( 1 )->push( 2 )->push( 3 )->push( 4 ).
write: |push 1, push 2, push 3, push 4 -> Stack2 = { stack2->stringify( ) }|, /.
stack2->pop( )->pop( importing top_element = top_integer ).
write: |pop, pop and return element -> { top_integer }, Stack2 = { stack2->stringify( ) }|, /, /.
 
write: |Stack3 = { stack3->stringify( ) }|, /.
stack3->pop( ).
write: |pop -> Stack3 = { stack3->stringify( ) }|, /, /.
</syntaxhighlight>
 
{{out}}
<pre>
Stack1 = empty
 
push a, push b, push c, push d -> Stack1 = dcba
 
pop, pop and return element -> c, Stack1 = ba
 
 
Stack2 = empty
 
push 1, push 2, push 3, push 4 -> Stack2 = 4321
 
pop, pop and return element -> 3, Stack2 = 21
 
 
Stack3 = empty
 
pop -> Stack3 = empty
</pre>
 
=={{header|Action!}}==
===Static memory===
<syntaxhighlight lang="action!">DEFINE MAXSIZE="200"
BYTE ARRAY stack(MAXSIZE)
BYTE stacksize=[0]
 
BYTE FUNC IsEmpty()
IF stacksize=0 THEN
RETURN (1)
FI
RETURN (0)
 
PROC Push(BYTE v)
IF stacksize=maxsize THEN
PrintE("Error: stack is full!")
Break()
FI
stack(stacksize)=v
stacksize==+1
RETURN
 
BYTE FUNC Pop()
IF IsEmpty() THEN
PrintE("Error: stack is empty!")
Break()
FI
stacksize==-1
RETURN (stack(stacksize))
 
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Stack is empty")
ELSE
PrintE("Stack is not empty")
FI
RETURN
 
PROC TestPush(BYTE v)
PrintF("Push: %B%E",v)
Push(v)
RETURN
 
PROC TestPop()
BYTE v
 
Print("Pop: ")
v=Pop()
PrintBE(v)
RETURN
 
PROC Main()
TestIsEmpty()
TestPush(10)
TestIsEmpty()
TestPush(31)
TestPop()
TestIsEmpty()
TestPush(5)
TestPop()
TestPop()
TestPop()
RETURN</syntaxhighlight>
 
===Dynamic memory===
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT
 
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
 
DEFINE PTR="CARD"
DEFINE NODE_SIZE="3"
TYPE StackNode=[BYTE data PTR nxt]
 
StackNode POINTER stack
 
BYTE FUNC IsEmpty()
IF stack=0 THEN
RETURN (1)
FI
RETURN (0)
 
PROC Push(BYTE v)
StackNode POINTER node
 
node=Alloc(NODE_SIZE)
node.data=v
node.nxt=stack
stack=node
RETURN
 
BYTE FUNC Pop()
StackNode POINTER node
BYTE v
IF IsEmpty() THEN
PrintE("Error stack is empty!")
Break()
FI
 
node=stack
v=node.data
stack=node.nxt
Free(node,NODE_SIZE)
RETURN (v)
 
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Stack is empty")
ELSE
PrintE("Stack is not empty")
FI
RETURN
 
PROC TestPush(BYTE v)
PrintF("Push: %B%E",v)
Push(v)
RETURN
 
PROC TestPop()
BYTE v
 
Print("Pop: ")
v=Pop()
PrintBE(v)
RETURN
 
PROC Main()
AllocInit(0)
stack=0
 
Put(125) PutE() ;clear screen
 
TestIsEmpty()
TestPush(10)
TestIsEmpty()
TestPush(31)
TestPop()
TestIsEmpty()
TestPush(5)
TestPop()
TestPop()
TestPop()
RETURN</syntaxhighlight>
{{out}}
Error at the end of program is intentional.
 
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Stack_array.png Screenshot from Atari 8-bit computer]
<pre>
Stack is empty
Push: 10
Stack is not empty
Push: 31
Pop: 31
Stack is not empty
Push: 5
Pop: 5
Pop: 10
Pop: Error: stack is empty!
 
RETURN
Error: 128
</pre>
 
=={{header|ActionScript}}==
In ActionScript an Array object provides stack functionality.
<langsyntaxhighlight lang="actionscript">var stack:Array = new Array();
stack.push(1);
stack.push(2);
trace(stack.pop()); // outputs "2"
trace(stack.pop()); // outputs "1"</langsyntaxhighlight>
 
=={{header|Ada}}==
This is a generic stack implementation.
<langsyntaxhighlight lang="ada">generic
type Element_Type is private;
package Generic_Stack is
Line 42 ⟶ 551:
Next : Stack := null;
end record;
end Generic_Stack;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">with Ada.Unchecked_Deallocation;
 
package body Generic_Stack is
Line 84 ⟶ 593:
end Pop;
 
end Generic_Stack;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
===ALGOL 68: Using linked list===
ALGOL 68 uses "HEAP" variables for new LINKs in a linked list. Generally ALGOL 68's
[[garbage collection|garbage collector]] should recover the LINK memory some time after a value is popped.
Line 92 ⟶ 602:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.7 algol68g-2.7].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude/next_link.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJVALUE = ~ # Mode/type of actual obj to be stacked #
Line 106 ⟶ 616:
 
PROC obj nextlink free = (REF OBJNEXTLINK free)VOID:
next OF free := obj stack empty # give the garbage collector a BIG hint #</langsyntaxhighlight>'''File: prelude/stack_base.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJNEXTLINK = STRUCT(
Line 162 ⟶ 672:
self IS obj stack empty;
 
SKIP</langsyntaxhighlight>'''File: test/data_stigler_diet.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
MODE DIETITEM = STRUCT(
STRING food, annual quantity, units, REAL cost
Line 176 ⟶ 686:
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
)</langsyntaxhighlight>'''File: test/stack.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 195 ⟶ 705:
# OR example stack ISNT obj stack empty #
printf((diet item fmt, obj stack pop(example stack), $l$))
OD</syntaxhighlight>
OD</lang>'''Output:'''
{{out}}
<pre>
Items popped in reverse:
Line 206 ⟶ 717:
</pre>
'''See also:''' [[Queue#ALGOL_68|Queue]]
===ALGOL 68: Using FLEX array===
An alternative to using a linked list is to use a FLEX array.
<syntaxhighlight lang="algol68">
MODE DIETITEM = STRUCT (
STRING food, annual quantity, units, REAL cost
);
MODE OBJVALUE = DIETITEM;
 
# PUSH element to stack #
OP +:= = (REF FLEX[]OBJVALUE stack, OBJVALUE item) VOID:
BEGIN
FLEX[UPB stack + 1]OBJVALUE newstack;
newstack[2:UPB newstack] := stack;
newstack[1] := item;
stack := newstack
END;
 
OP POP = (REF FLEX[]OBJVALUE stack) OBJVALUE:
IF UPB stack > 0 THEN
OBJVALUE result = stack[1];
stack := stack[2:UPB stack];
result
ELSE
# raise index error; # SKIP
FI;
 
# Stigler's 1939 Diet ... #
FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$;
[]DIETITEM stigler diet = (
("Cabbage", "111","lb.", 4.11),
("Dried Navy Beans", "285","lb.", 16.80),
("Evaporated Milk", "57","cans", 3.84),
("Spinach", "23","lb.", 1.85),
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
);
 
FLEX[0]DIETITEM example stack;
FOR i TO UPB stigler diet DO
example stack +:= stigler diet[i]
OD;
printf($"Items popped in reverse:"l$);
WHILE UPB example stack > 0 DO
printf((diet item fmt, POP example stack, $l$))
OD
</syntaxhighlight>
{{out}}
<pre>
Items popped in reverse:
Total Annual Cost: = $39.93
Wheat Flour: 370 lb. = $13.33
Spinach: 23 lb. = $ 1.85
Evaporated Milk: 57 cans = $ 3.84
Dried Navy Beans: 285 lb. = $16.80
Cabbage: 111 lb. = $ 4.11
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% define a Stack type that will hold StringStackElements %
% and the StringStackElement type %
% we would need separate types for other element types %
record StringStack ( reference(StringStackElement) top );
record StringStackElement ( string(8) element
; reference(StringStackElement) next
);
% adds e to the end of the StringStack s %
procedure pushString ( reference(StringStack) value s
; string(8) value e
) ;
top(s) := StringStackElement( e, top(s) );
% removes and returns the top element from the StringStack s %
% asserts the Stack is not empty, which will stop the %
% program if it is %
string(8) procedure popString ( reference(StringStack) value s ) ;
begin
string(8) v;
assert( not isEmptyStringStack( s ) );
v := element(top(s));
top(s):= next(top(s));
v
end popStringStack ;
% returns the top element of the StringStack s %
% asserts the Stack is not empty, which will stop the %
% program if it is %
string(8) procedure peekStringStack ( reference(StringStack) value s ) ;
begin
assert( not isEmptyStringStack( s ) );
element(top(s))
end popStringStack ;
% returns true if the StringStack s is empty, false otherwise %
logical procedure isEmptyStringStack ( reference(StringStack) value s ) ; top(s) = null;
begin % test the StringStack operations %
reference(StringStack) s;
s := StringStack( null );
pushString( s, "up" );
pushString( s, "down" );
pushString( s, "strange" );
pushString( s, "charm" );
while not isEmptyStringStack( s ) do write( popString( s )
, if isEmptyStringStack( s ) then "(empty)"
else peekStringStack( s )
)
end
end.</syntaxhighlight>
{{out}}
<pre>
charm strange
strange down
down up
up (empty)
</pre>
 
=={{header|Applesoft BASIC}}==
<langsyntaxhighlight lang="basic">100 DIM STACK$(1000)
110 DATA "(2*A)","PI","","TO BE OR","NOT TO BE"
120 FOR I = 1 TO 5
Line 247 ⟶ 874:
730 LET EMPTY = SP = 0
740 RETURN
</syntaxhighlight>
</lang>
 
{{out}}
Line 258 ⟶ 885:
STACK IS EMPTY
</pre>
 
=={{header|ARM Assembly}}==
The stack is held in register 13, or <code>r13</code> but more commonly referred to as <code>SP</code> for clarity.
 
Pushing and popping multiple values is very similar to [[68000 Assembly]].
<syntaxhighlight lang="arm assembly">STMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register
LDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is put into the program counter.
;This acts as a pop and return command all-in-one. (Most programs use bx lr to return.)</syntaxhighlight>
 
Like in 68000 Assembly, you are not limited to using <code>SP</code> as the source/destination for these commands; any register can fulfill that role. If you wish to have multiple stacks, then so be it.
 
The stack pointer will work with any operation the other registers can. As such, a peek can be done by using an <code>LDR</code> with the stack pointer as the address register:
 
<syntaxhighlight lang="arm assembly">LDR r0,[sp] ;load the top of the stack into r0</syntaxhighlight>
 
The order in which registers are pushed/popped is always the same, no matter which order you list the registers in your source code. If you want to push some registers and purposefully pop them into different registers, you'll need to push/pop them separately.
 
A check if the stack is empty is also very simple, provided the initial value of the stack pointer was saved at the start of the program, or (more likely) was loaded from a nearby memory location.
 
<syntaxhighlight lang="arm assembly">;this example uses VASM syntax which considers a "word" to be 16-bit regardless of the architecture
InitStackPointer: .long 0x3FFFFFFF ;other assemblers would call this a "word"
 
MOV R1,#InitStackPointer
LDR SP,[R1] ;set up the stack pointer
LDR R2,[R1] ;also load it into R2
;There's no point in checking since we haven't pushed/popped anything but just for demonstration purposes we'll check now
CMP SP,R2
BEQ StackIsEmpty</syntaxhighlight>
 
In THUMB mode, the <code>PUSH</code> and <code>POP</code> commands replace <code>STMFD</code> and <code>LDMFD</code>. They work in a similar fashion, but are limited to just the stack unlike the real <code>STMFD</code> and <code>LDMFD</code> commands which can use any register as the "stack pointer."
 
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">Stack: $[]-> []
 
pushTo: function [st val]-> 'st ++ val
popStack: function [st] [
result: last st
remove 'st .index (size st)-1
return result
]
emptyStack: function [st]-> empty 'st
printStack: function [st]-> print st
 
st: new Stack
 
pushTo st "one"
pushTo st "two"
pushTo st "three"
printStack st
 
print popStack st
printStack st
 
emptyStack st
print ["finally:" st]</syntaxhighlight>
 
{{out}}
 
<pre>one two three
three
one two
finally: []</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">(* Stacks implemented as linked lists. *)
 
(* A nonlinear stack type of size n, which is good for when you are
using a garbage collector or can let the memory leak. *)
typedef stack_t (t : t@ype+, n : int) = list (t, n)
typedef stack_t (t : t@ype+) = [n : int] stack_t (t, n)
 
(* A linear stack type of size n, which requires (and will enforce)
explicit freeing. (Note that a "peek" function for a linear stack
is a complicated topic. But the task avoids this issue.) *)
viewtypedef stack_vt (vt : vt@ype+, n : int) = list_vt (vt, n)
viewtypedef stack_vt (vt : vt@ype+) = [n : int] stack_vt (vt, n)
 
(* Proof that a given nonlinear stack does not have a nonnegative
size. *)
prfn
lemma_stack_t_param {n : int} {t : t@ype}
(stack : stack_t (t, n)) :<prf>
[0 <= n] void =
lemma_list_param stack
 
(* Proof that a given linear stack does not have a nonnegative
size. *)
prfn
lemma_stack_vt_param {n : int} {vt : vt@ype}
(stack : !stack_vt (vt, n)) :<prf>
[0 <= n] void =
lemma_list_vt_param stack
 
(* Create an empty nonlinear stack. *)
fn {}
stack_t_nil {t : t@ype} () :<> stack_t (t, 0) =
list_nil ()
 
(* Create an empty linear stack. *)
fn {}
stack_vt_nil {vt : vt@ype} () :<> stack_vt (vt, 0) =
list_vt_nil ()
 
(* Is a nonlinear stack empty? *)
fn {}
stack_t_is_empty {n : int} {t : t@ype}
(stack : stack_t (t, n)) :<>
[empty : bool | empty == (n == 0)]
bool empty =
case+ stack of
| list_nil _ => true
| list_cons _ => false
 
(* Is a linear stack empty? *)
fn {}
stack_vt_is_empty {n : int} {vt : vt@ype}
(* ! = pass by value; stack is preserved. *)
(stack : !stack_vt (vt, n)) :<>
[empty : bool | empty == (n == 0)]
bool empty =
case+ stack of
| list_vt_nil _ => true
| list_vt_cons _ => false
 
(* Push to a nonlinear stack that is stored in a variable. *)
fn {t : t@ype}
stack_t_push {n : int}
(stack : &stack_t (t, n) >> stack_t (t, m),
x : t) :<!wrt>
(* It is proved that the stack is raised one higher. *)
#[m : int | 1 <= m; m == n + 1]
void =
let
prval _ = lemma_stack_t_param stack
prval _ = prop_verify {0 <= n} ()
in
stack := list_cons (x, stack)
end
 
(* Push to a linear stack that is stored in a variable. Beware: if x
is linear, it is consumed. *)
fn {vt : vt@ype}
stack_vt_push {n : int}
(stack : &stack_vt (vt, n) >> stack_vt (vt, m),
x : vt) :<!wrt>
(* It is proved that the stack is raised one higher. *)
#[m : int | 1 <= m; m == n + 1]
void =
let
prval _ = lemma_stack_vt_param stack
prval _ = prop_verify {0 <= n} ()
in
stack := list_vt_cons (x, stack)
end
 
(* Pop from a nonlinear stack that is stored in a variable. It is
impossible (unless you cheat the typechecker) to pop from an empty
stack. *)
fn {t : t@ype}
stack_t_pop {n : int | 1 <= n}
(stack : &stack_t (t, n) >> stack_t (t, m)) :<!wrt>
(* It is proved that the stack is lowered by one. *)
#[m : int | m == n - 1]
t =
case+ stack of
| list_cons (x, tail) =>
begin
stack := tail;
x
end
 
(* Pop from a linear stack that is stored in a variable. It is
impossible (unless you cheat the typechecker) to pop from an empty
stack. *)
fn {vt : vt@ype}
stack_vt_pop {n : int | 1 <= n}
(stack : &stack_vt (vt, n) >> stack_vt (vt, m)) :<!wrt>
(* It is proved that the stack is lowered by one. *)
#[m : int | m == n - 1]
vt =
case+ stack of
| ~ list_vt_cons (x, tail) => (* ~ = the top node is consumed. *)
begin
stack := tail;
x
end
 
(* A linear stack has to be consumed. *)
extern fun {vt : vt@ype}
stack_vt_free$element_free (x : vt) :<> void
fn {vt : vt@ype}
stack_vt_free {n : int}
(stack : stack_vt (vt, n)) :<> void =
let
fun
loop {m : int | 0 <= m}
.<m>. (* <-- proof of loop termination *)
(stk : stack_vt (vt, m)) :<> void =
case+ stk of
| ~ list_vt_nil () => begin end
| ~ list_vt_cons (x, tail) =>
begin
stack_vt_free$element_free x;
loop tail
end
 
prval _ = lemma_stack_vt_param stack
in
loop stack
end
 
implement
main0 () =
let
var nonlinear_stack : stack_t (int) = stack_t_nil ()
var linear_stack : stack_vt (int) = stack_vt_nil ()
implement stack_vt_free$element_free<int> x = begin end
 
overload is_empty with stack_t_is_empty
overload is_empty with stack_vt_is_empty
 
overload push with stack_t_push
overload push with stack_vt_push
 
overload pop with stack_t_pop
overload pop with stack_vt_pop
in
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
 
println! ("pushing 3, 2, 1...");
push (nonlinear_stack, 3);
push (nonlinear_stack, 2);
push (nonlinear_stack, 1);
push (linear_stack, 3);
push (linear_stack, 2);
push (linear_stack, 1);
 
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
 
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
println! ("popping nonlinear_stack: ", (pop nonlinear_stack) : int);
 
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
println! ("popping linear_stack: ", (pop linear_stack) : int);
 
println! ("nonlinear_stack is empty? ", is_empty nonlinear_stack);
println! ("linear_stack is empty? ", is_empty linear_stack);
 
stack_vt_free<int> linear_stack
end</syntaxhighlight>
 
{{out}}
<pre>$ patscc -O2 -DATS_MEMALLOC_LIBC stack-postiats.dats && ./a.out
nonlinear_stack is empty? true
linear_stack is empty? true
pushing 3, 2, 1...
nonlinear_stack is empty? false
linear_stack is empty? false
popping nonlinear_stack: 1
popping nonlinear_stack: 2
popping nonlinear_stack: 3
popping linear_stack: 1
popping linear_stack: 2
popping linear_stack: 3
nonlinear_stack is empty? true
linear_stack is empty? true</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">msgbox % stack("push", 4)
msgbox % stack("push", 5)
msgbox % stack("peek")
Line 298 ⟶ 1,195:
return 0
}
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">function deque(arr) {
arr["start"] = 0
arr["end"] = 0
}
 
function dequelen(arr) {
return arr["end"] - arr["start"]
}
 
function empty(arr) {
return dequelen(arr) == 0
}
 
function push(arr, elem) {
arr[++arr["end"]] = elem
}
 
function pop(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]--]
}
 
function unshift(arr, elem) {
arr[arr["start"]--] = elem
}
 
function shift(arr) {
if (empty(arr)) {
return
}
return arr[++arr["start"]]
}
 
function peek(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]]
}
 
function printdeque(arr, i, sep) {
printf("[")
for (i = arr["start"] + 1; i <= arr["end"]; i++) {
printf("%s%s", sep, arr[i])
sep = ", "
}
printf("]\n")
}
 
BEGIN {
deque(q)
for (i = 1; i <= 10; i++) {
push(q, i)
}
printdeque(q)
for (i = 1; i <= 10; i++) {
print pop(q)
}
printdeque(q)
}</syntaxhighlight>
 
=={{header|Axe}}==
 
<syntaxhighlight lang="axe">0→S
Lbl PUSH
r₁→{L₁+S}ʳ
S+2→S
Return
 
Lbl POP
S-2→S
{L₁+S}ʳ
Return
 
Lbl EMPTY
S≤≤0
Return</syntaxhighlight>
 
=={{header|Babel}}==
<langsyntaxhighlight lang="babel">main :
{ (1 2 3) foo set -- foo = (1 2 3)
4 foo push -- foo = (1 2 3 4)
Line 318 ⟶ 1,296:
"empty" .
cr << }
</syntaxhighlight>
 
{{out}}
Output:
<pre>
foo is not empty
foo is empty</langpre>
 
=={{header|Batch File}}==
This implementation uses an environment variable naming convention to implement a stack as a pseudo object containing a pseudo dynamic array and top attribute, as well as an empty "method" that is a sort of macro. The implementation depends on delayed expansion being enabled at the time of each call to a stack function. More complex variations can be written that remove this limitation.
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
 
Line 393 ⟶ 1,372:
if !%~1.top! equ 0 exit /b 1
for %%N in (!%~1.top!) do set %~2=!%~1.%%N!
exit /b 0</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> STACKSIZE = 1000
FOR n = 3 TO 5
Line 427 ⟶ 1,407:
= (sptr% = 0)
ENDCASE
ENDPROC</langsyntaxhighlight>
{{out}}
'''Output:'''
<pre>
Push 3
Line 441 ⟶ 1,421:
Error: stack empty
</pre>
 
=={{header|beeswax}}==
Beeswax is a stack-based language. The instruction pointers (bees) carry small local stacks (lstacks) of fixed length 3 that can interact with the global stack (gstack) of unrestricted length. The local stacks do not behave exactly like the stack specified in this task, but the global stack does.
 
'''Push (1)''': <code>f</code> pushes the topmost value of lstack on gstack.
<pre> instruction: _f
 
gstack: UInt64[0]• (at the beginning of a program lstack is initialized to [0 0 0]</pre>
 
'''Push (2)''': <code>e</code> pushes all three lstack values on gstack, in reversed order.
<pre> instruction: _e
 
gstack: UInt64[0 0 0]• (at the beginning of a program lstack is initialized to [0 0 0]</pre>
 
'''Push (3)''': <code>i</code> pushes an integer from STDIN as UInt64 value on gstack.
<pre> instruction: _i
input: i123
 
gstack: UInt64[123]•</pre>
 
'''Push (4)''': <code>c</code> pushes the Unicode codepoint value of a character from STDIN as UInt64 value on gstack.
<pre> instruction: _c
input: cH
 
gstack: UInt64[72]•</pre>
 
'''Push (5)''': <code>V</code> pushes the Unicode codepoint values of the characters of a string given at STDIN as UInt64 values on gstack, last character, followed by newline on top.
<pre> instruction: _V
input: sHello, α∀
 
gstack: UInt64[72 101 108 108 111 44 32 945 8704 10]•</pre>
 
'''Pop''': <code>g{?</code> reads the top value of gstack and stores it on top of lstack. Then outputs top value of lstack to STDOUT and finally pops gstack.
 
'''Empty''': <code>Ag?';`gstack is empty`</code> pushes length of gstack on gstack, reads top value of gstack, stores it as top value of lstack and prints <code>gstack is empty</code> if lstack top=0.
 
'''Top''': <code>g{</code> reads the top value of gstack, stores it on top of lstack. Then outputs top value of lstack to STDOUT. If gstack is empty, this instruction does not do anything but return the topmost value of lstack.
 
To make sure that there is any value on gstack, you would need to check for gstack length first, using the method shown in the “'''Empty'''” example above:
<pre>*Ag'{`gstack empty, no value to return`</pre>
This method returns the top value of gstack only if gstack is not empty, otherwise it outputs <code>gstack empty, no value to return</code> to STDOUT.
 
=={{header|BQN}}==
Representing the stack as an array, pushing is appending, popping is removing the last element, and checking emptiness is checking the length.
 
<syntaxhighlight lang="bqn"> Push ← ∾
Pop ← ¯1⊸↓
¯1⊸↓
Empty ← 0=≠
0=≠
1‿2‿3 Push 4
⟨ 1 2 3 4 ⟩
Pop 1‿2‿3
⟨ 1 2 ⟩
Empty 1‿2‿3
0
Empty ⟨⟩
1</syntaxhighlight>
 
=={{header|Bracmat}}==
A stack is easiest implemented as a dotted list <code>top.top-1.top-2.<i>[...]</i>.</code>. In the example below we also introduce a 'class' <code>stack</code>, instantiated in the 'object' <code>Stack</code>. The class has a member variable <code>S</code> and methods <code>push</code>,<code>pop</code>, <code>top</code> and <code>empty</code>. As a side note, <code>.</code> is to <code>..</code> as C's <code>.</code> is to <code>-&gt;</code>. In a method's body, <code>its</code> refers to the object itself. (Analogous to <code>(*this)</code> in C++.)
<langsyntaxhighlight lang="bracmat">( ( stack
= (S=)
(push=.(!arg.!(its.S)):?(its.S))
Line 475 ⟶ 1,514:
)
&
);</langsyntaxhighlight>
{{out}}
Output:
<pre>not to be
to be or
Line 490 ⟶ 1,529:
Built in arrays have push, pop, and empty? methods:
 
<langsyntaxhighlight Bratlang="brat">stack = []
stack.push 1
stack.push 2
stack.push 3
 
until { stack.empty? } { p stack.pop }</langsyntaxhighlight>
 
{{out}}
Output:
<pre>3
2
Line 504 ⟶ 1,543:
=={{header|C}}==
Macro expanding to type flexible stack routines.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 565 ⟶ 1,604:
stk_int_delete(stk);
return 0;
}</langsyntaxhighlight>
===Or===
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
Line 637 ⟶ 1,676:
s->bottom = realloc(s->bottom, new_size);
check_pointer(s->bottom);
s->allocated_top = s->bottom + qtty - 1;}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">// Non-Generic Stack
System.Collections.Stack stack = new System.Collections.Stack();
stack.Push( obj );
Line 652 ⟶ 1,691:
bool isEmpty = stack.Count == 0;
Foo top = stack.Peek(); // Peek without Popping.
top = stack.Pop();</langsyntaxhighlight>
 
=={{header|C++}}==
{{libheader|STL}}
The C++ standard library already provides a ready-made stack class. You get it by writing
<syntaxhighlight lang ="cpp">#include <stack></langsyntaxhighlight>
and then using the <tt>std::stack</tt> class.
 
An example of an explicit implementation of a stack class (which actually implements the standard stack class, except that the standard one is in namespace std):
<langsyntaxhighlight lang="cpp">#include <deque>
template <class T, class Sequence = std::deque<T> >
class stack {
Line 715 ⟶ 1,754:
{
return !(x < y);
}</langsyntaxhighlight>
 
== {{header|Clojure}} ==
As is mentioned in the Common Lisp example below, built in cons-based lists work just fine. In this implementation, the list is wrapped in a datatype, providing a stateful solution.
<langsyntaxhighlight lang="lisp">(deftype Stack [elements])
 
(def stack (Stack (ref ())))
Line 738 ⟶ 1,777:
(defn empty-stack?
"Tests whether or not the stack is empty."
[] (= () (deref (:elements stack))))</langsyntaxhighlight>
 
We can make this a bit smaller and general by using defprotocol along with deftype. Here is a revised version using defprotocol.
 
<langsyntaxhighlight lang="lisp">(defprotocol StackOps
(push-stack [this x] "Pushes an item to the top of the stack.")
(pop-stack [this] "Pops an item from the top of the stack.")
Line 755 ⟶ 1,794:
(empty-stack? [] (= () (deref elements))))
 
(def stack (Stack (ref ())))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Stack
stack = cluster [T: type] is new, push, pop, peek, empty
rep = array[T]
new = proc () returns (cvt)
return (rep$new())
end new
empty = proc (s: cvt) returns (bool)
return (rep$size(s) = 0)
end empty;
push = proc (s: cvt, val: T)
rep$addh(s, val)
end push;
pop = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(rep$remh(s))
end
end pop
peek = proc (s: cvt) returns (T) signals (empty)
if rep$empty(s)
then signal empty
else return(s[rep$high(s)])
end
end peek
end stack
 
start_up = proc ()
po: stream := stream$primary_output()
% Make a stack
s: stack[int] := stack[int]$new()
% Push 1..10 onto the stack
for i: int in int$from_to(1, 10) do
stack[int]$push(s, i)
end
% Pop items off the stack until the stack is empty
while ~stack[int]$empty(s) do
stream$putl(po, int$unparse(stack[int]$pop(s)))
end
% Trying to pop off the stack now should raise 'empty'
begin
i: int := stack[int]$pop(s)
stream$putl(po, "Still here! And I got: " || int$unparse(i))
end except when empty:
stream$putl(po, "The stack is empty.")
end
end start_up</syntaxhighlight>
{{out}}
<pre>10
9
8
7
6
5
4
3
2
1
The stack is empty.</pre>
 
=={{header|COBOL}}==
Line 766 ⟶ 1,874:
 
stack.cbl
<langsyntaxhighlight COBOLlang="cobol"> 01 stack.
05 head USAGE IS POINTER VALUE NULL.
</syntaxhighlight>
</lang>
 
node.cbl
<langsyntaxhighlight COBOLlang="cobol"> 01 node BASED.
COPY node-info REPLACING
01 BY 05
node-info BY info.
05 link USAGE IS POINTER VALUE NULL.
</syntaxhighlight>
</lang>
 
node-info.cbl
<langsyntaxhighlight COBOLlang="cobol"> 01 node-info PICTURE X(10) VALUE SPACES.
</syntaxhighlight>
</lang>
 
p.cbl
<langsyntaxhighlight COBOLlang="cobol"> 01 p PICTURE 9.
88 nil VALUE ZERO WHEN SET TO FALSE IS 1.
88 t VALUE 1 WHEN SET TO FALSE IS ZERO.
</syntaxhighlight>
</lang>
 
stack-utilities.cbl
<langsyntaxhighlight COBOLlang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. push.
DATA DIVISION.
Line 1,036 ⟶ 2,144:
GOBACK.
END PROGRAM traverse-stack.
</syntaxhighlight>
</lang>
 
stack-test.cbl
<langsyntaxhighlight COBOLlang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. stack-test.
DATA DIVISION.
Line 1,076 ⟶ 2,184:
 
COPY stack-utilities.
</syntaxhighlight>
</lang>
 
{{out}}
Output:
<pre>
aleph
Line 1,106 ⟶ 2,214:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight CoffeeScriptlang="coffeescript">stack = []
stack.push 1
stack.push 2
console.log stack
console.log stack.pop()
console.log stack</langsyntaxhighlight>
 
== {{header|Common Lisp}} ==
It's a bit unusual to write a wrapper for a stack in Common Lisp; built-in cons-based lists work just fine. Nonetheless, here's an implementation where the list is wrapped in a structure, providing a stateful solution.
<langsyntaxhighlight lang="lisp">(defstruct stack
elements)
 
Line 1,130 ⟶ 2,238:
 
(defun stack-peek (stack)
(stack-top stack))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
Works with BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Stacks;
IMPORT StdLog;
Line 1,244 ⟶ 2,353:
END Stacks.
</syntaxhighlight>
</lang>
 
Execute: ^Q Stacks.TestStack<br/>
{{out}}
Output:
<pre>
Point( 2.0, 3.4);
Integer( 1);
</pre>
 
=={{header|Crystal}}==
 
<syntaxhighlight lang="ruby">stack = [] of Int32
(1..10).each do |x|
stack.push x
end
 
10.times do
puts stack.pop
end</syntaxhighlight>
 
'''Output:'''
 
<pre>
10
9
8
7
6
5
4
3
2
1
</pre>
 
=={{header|D}}==
Generic stack class implemented with a dynamic array.
<langsyntaxhighlight lang="d">import std.array;
 
class Stack(T) {
Line 1,279 ⟶ 2,415:
assert(s.pop() == 10);
assert(s.empty());
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program Stack;
 
{$APPTYPE CONSOLE}
Line 1,305 ⟶ 2,441:
lStack.Free;
end;
end.</langsyntaxhighlight>
 
=={{header|DWScript}}==
Dynamic arrays have pseudo-methods that allow to treat them as a stack.
<syntaxhighlight lang="delphi">
var stack: array of Integer;
 
stack.Push(1);
stack.Push(2);
stack.Push(3);
 
PrintLn(stack.Pop); // 3
PrintLn(stack.Pop); // 2
PrintLn(stack.Pop); // 1
 
Assert(stack.Length = 0); // assert empty
</syntaxhighlight>
 
=={{header|Dyalect}}==
 
{{trans|Swift}}
 
<syntaxhighlight lang="dyalect">type Stack() {
var xs = []
}
func Stack.IsEmpty() => this!xs.Length() == 0
func Stack.Peek() => this!xs[this!xs.Length() - 1]
func Stack.Pop() {
var e = this!xs[this!xs.Length() - 1]
this!xs.RemoveAt(this!xs.Length() - 1)
return e
}
func Stack.Push(item) => this!xs.Add(item)
var stack = Stack()
stack.Push(1)
stack.Push(2)
print(stack.Pop())
print(stack.Peek())
stack.Pop()
print(stack.IsEmpty())</syntaxhighlight>
 
{{out}}
 
<pre>2
1
true</pre>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :stack [] #lists used to be stacks in DV
 
push-to stack 1
Line 1,318 ⟶ 2,505:
 
if stack: #empty lists are falsy
error #this stack should be empty now!</langsyntaxhighlight>
 
=={{header|DWScriptDiego}}==
Diego has a <code>stack</code> object and posit:
Dynamic arrays have pseudo-methods that allow to treat them as a stack.
<syntaxhighlight lang="diego">set_ns(rosettacode)_me();
<lang Delphi>
var stack: array of Integer;
 
add_stack({int},a)_values(1..4); // 1,2,3,4 (1 is first/bottom, 4 is last/top)
stack.Push(1);
with_stack(a)_pop(); // 1,2,3
stack.Push(2);
with_stack(a)_push()_v(5,6); // 1,2,3,5,6
stack.Push(3);
 
add_var({int},b)_value(7);
PrintLn(stack.Pop); // 3
with_stack(a)_push[b]; // 1,2,3,5,6,7
PrintLn(stack.Pop); // 2
PrintLn(stack.Pop); // 1
 
with_stack(a)_pluck()_at(2); // callee will return `with_stack(a)_err(pluck invalid with stack);`
Assert(stack.Length = 0); // assert empty
 
</lang>
me_msg()_stack(a)_top(); // "7"
me_msg()_stack(a)_last(); // "7"
me_msg()_stack(a)_peek(); // "7"
 
me_msg()_stack(a)_bottom(); // "1"
me_msg()_stack(a)_first(); // "1"
me_msg()_stack(a)_peer(); // "1"
 
me_msg()_stack(a)_isempty(); // "false"
with_stack(a)_empty();
with_stack(a)_msg()_isempty()_me(); // "true" (alternative syntax)
 
me_msg()_stack(a)_history()_all(); // returns th entire history of stack 'a' since its creation
 
reset_ns[];</syntaxhighlight>
<code>stack</code> is a derivative of <code>array</code>, so arrays can also be used as stacks.
 
=={{header|E}}==
The standard FlexList data structure provides operations for use as a stack.
<langsyntaxhighlight lang="e">? def l := [].diverge()
# value: [].diverge()
 
Line 1,359 ⟶ 2,560:
 
? l.size().aboveZero()
# value: false</langsyntaxhighlight>
Here's a stack implemented out of a reference to a linked list:
<langsyntaxhighlight lang="e">def makeStack() {
var store := null
def stack {
Line 1,390 ⟶ 2,591:
 
? s.empty()
# value: true</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
stack[] = [ ]
proc push v . .
stack[] &= v
.
func pop .
lng = len stack[]
if lng = 0
return 0
.
r = stack[lng]
len stack[] -1
return r
.
func empty .
return if len stack[] = 0
.
push 2
push 11
push 34
while empty = 0
print pop
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Named stacks are native objects. The following demonstrates the available operations :
<syntaxhighlight lang="lisp">
; build stack [0 1 ... 9 (top)] from a list
(list->stack (iota 10) 'my-stack)
(stack-top 'my-stack) → 9
(pop 'my-stack) → 9
(stack-top 'my-stack) → 8
(push 'my-stack '🐸) ; any kind of lisp object in the stack
(stack-empty? 'my-stack) → #f
(stack->list 'my-stack) ; convert stack to list
→ (0 1 2 3 4 5 6 7 8 🐸)
(stack-swap 'my-stack) ; swaps two last items
→ 8 ; new top
(stack->list 'my-stack)
→ (0 1 2 3 4 5 6 7 🐸 8) ; swapped
(while (not (stack-empty? 'my-stack)) (pop 'my-stack)) ; pop until empty
(stack-empty? 'my-stack) → #t ; true
 
(push 'my-stack 7)
my-stack ; a stack is not a variable, nor a symbol - cannot be evaluated
⛔ error: #|user| : unbound variable : my-stack
(stack-top 'my-stack) → 7
</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
STACK_ON_ARRAY
Line 1,437 ⟶ 2,689:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
<syntaxhighlight lang="elena">public program()
{
var stack := new system'collections'Stack();
stack.push(2);
var isEmpty := stack.Length == 0;
var item := stack.peek(); // Peek without Popping.
item := stack.pop()
}</syntaxhighlight>
 
=={{header|Elisa}}==
This is a generic Stack component based on arrays. See how in Elisa [http://jklunder.home.xs4all.nl/elisa/part01/doc120.html generic components] are defined.
<langsyntaxhighlight Elisalang="elisa"> component GenericStack ( Stack, Element );
type Stack;
Stack (MaxSize = integer) -> Stack;
Line 1,461 ⟶ 2,727:
stack.index:=stack.index - 1;
stack.area[stack.index + 1] ];
end component GenericStack;</langsyntaxhighlight>
Another example of a generic Stack component is based on an unlimited sequence. A sequence is a uni-directional list. See how Elisa defines [http://jklunder.home.xs4all.nl/elisa/part02/doc010.html sequences]. The component has the same interface as the array based version.
<langsyntaxhighlight Elisalang="elisa">component GenericStack ( Stack, ElementType );
type Stack;
Stack(MaxSize = integer) -> Stack;
Line 1,487 ⟶ 2,753:
Pull ( stack ) = [ exception (Empty (stack), "Stack Underflow");
Head = head(stack.list); stack.list:=tail(stack.list); Head];
end component GenericStack;</langsyntaxhighlight>
Both versions give the same answers to the following tests:
<langsyntaxhighlight Elisalang="elisa">use GenericStack (StackofBooks, Book);
type Book = text;
BookStack = StackofBooks(50);
Line 1,503 ⟶ 2,769:
 
Pull (BookStack)?
***** Exception: Stack Underflow</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule Stack do
def new, do: []
def empty?([]), do: true
def empty?(_), do: false
def pop([h|t]), do: {h,t}
def push(h,t), do: [h|t]
def top([h|_]), do: h
end</syntaxhighlight>
 
Example:
<pre>
iex(2)> stack = Stack.new
[]
iex(3)> Stack.empty?(stack)
true
iex(4)> newstack = List.foldl([1,2,3,4,5], stack, fn x,acc -> Stack.push(x,acc) end)
[5, 4, 3, 2, 1]
iex(5)> Stack.top(newstack)
5
iex(6)> {popped, poppedstack} = Stack.pop(newstack)
{5, [4, 3, 2, 1]}
iex(7)> Stack.empty?(newstack)
false
</pre>
 
=={{header|Erlang}}==
Erlang has no built-in stack, but its lists behave basically the same way. A stack module can be implemented as a simple wrapper around lists:
<langsyntaxhighlight lang="erlang">-module(stack).
-export([empty/1, new/0, pop/1, push/2, top/1]).
 
Line 1,519 ⟶ 2,816:
push(H,T) -> [H|T].
 
top([H|_]) -> H.</langsyntaxhighlight>
Note that as Erlang doesn't have mutable data structure (destructive updates), pop returns the popped element and the new stack as a tuple.
 
The module is tested this way:
<langsyntaxhighlight lang="erlang">1> c(stack).
{ok,stack}
2> Stack = stack:new().
Line 1,536 ⟶ 2,833:
false
7> stack:empty(stack:new()).
true</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
.NET provides a mutable stack type in <code>System.Collections.Generic.Stack</code>.
 
A list-based immutable stack type could be implemented like this:
<syntaxhighlight lang="fsharp">type Stack<'a> //'//(workaround for syntax highlighting problem)
(?items) =
let items = defaultArg items []
 
member x.Push(A) = Stack(A::items)
 
member x.Pop() =
match items with
| x::xr -> (x, Stack(xr))
| [] -> failwith "Stack is empty."
 
member x.IsEmpty() = items = []
 
// example usage
let anEmptyStack = Stack<int>()
let stack2 = anEmptyStack.Push(42)
printfn "%A" (stack2.IsEmpty())
let (x, stack3) = stack2.Pop()
printfn "%d" x
printfn "%A" (stack3.IsEmpty())</syntaxhighlight>
 
=={{header|Factor}}==
Factor is a stack based language, but also provides stack "objects", because
all resizable sequences can be treated as stacks (see [http://docs.factorcode.org/content/article-sequences-stacks.html docs]). Typically, a vector is used:
<langsyntaxhighlight lang="factor"> V{ 1 2 3 } {
[ 6 swap push ]
[ "hi" swap push ]
Line 1,552 ⟶ 2,874:
Let's pop it: "hi"
Vector is now: V{ 1 2 3 6 }
Top is: 6</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: stack ( size -- )
create here cell+ , cells allot ;
 
Line 1,569 ⟶ 2,891:
st empty? . \ 0 (false)
st pop . st pop . st pop . \ 3 2 1
st empty? . \ -1 (true)</langsyntaxhighlight>
 
=={{header|Fortran}}==
This solution can easily be adapted to data types other than integerfloating point numbers.
<langsyntaxhighlight lang="fortran">module stackmod_stack
 
implicit none
public
type node
! data entry in each node
real*8, private :: data
! pointer to the next node of the linked list
type(node), pointer, private :: next
end type node
private node
 
type stack
! Define the data-structure to hold the data
! pointer to first element of stack.
type stack_var
type(node), integerpointer, allocatableprivate :: data(:)first
integer ::! size =of 0stack
integer, private :: len=0
end type stack_var
contains
 
procedure :: pop
! Set the size of allocated memory blocks
procedure :: push
integer, parameter, private :: block_size = 10
procedure :: peek
procedure :: getSize
procedure :: clearStack
procedure :: isEmpty
end type stack
 
contains
 
function pop(this) result(x)
! Push ----------------------------------------------------------------------
class(stack) :: this
subroutine push(s, e)
type(stack_var), intent(inout)real*8 :: sx
integer, intenttype(innode), pointer :: etmp
if ( this%len == 0 ) then
integer, allocatable :: wk(:)
print*, "popping from empty stack"
if (.not. allocated(s%data)) then
!stop
! Allocate space if not yet done
allocate(s%data(block_size))
 
elseif (s%size == size(s%data)) then
! Grow the allocated space
allocate(wk(size(s%data)+block_size))
wk(1:s%size) = s%data
call move_alloc(wk,s%data)
 
end if
tmp => this%first
x = this%first%data
this%first => this%first%next
deallocate(tmp)
this%len = this%len -1
end function pop
 
subroutine push(this, x)
! Store the data in the stack
s%sizereal*8 =:: s%size + 1x
s%dataclass(s%sizestack), =target e:: this
type(node), pointer :: new, tmp
allocate(new)
new%data = x
if (.not. associated(this%first)) then
this%first => new
else
tmp => this%first
this%first => new
this%first%next => tmp
end if
this%len = this%len + 1
end subroutine push
 
function peek(this) result(x)
! Pop -----------------------------------------------------------------------
class(stack) :: this
function pop(s)
integerreal*8 :: popx
x = this%first%data
type(stack_var), intent(inout) :: s
end function peek
if (s%size == 0 .or. .not. allocated(s%data)) then
 
pop = 0
function getSize(this) result(n)
return
class(stack) :: this
integer :: n
n = this%len
end function getSize
 
function isEmpty(this) result(empty)
class(stack) :: this
logical :: empty
if ( this%len > 0 ) then
empty = .FALSE.
else
empty = .TRUE.
end if
end function isEmpty
pop = s%data(s%size)
s%size = s%size - 1
end function pop
 
subroutine clearStack(this)
! Peek ----------------------------------------------------------------------
class(stack) :: this
integer function peek(s)
type(stack_varnode), intent(inout)pointer :: stmp
integer :: i
if (s%size == 0 .or. .not. allocated(s%data)) then
if ( peekthis%len == 0 ) then
return
end if
peekdo i = s%data(s1, this%size)len
tmp => this%first
end function peek
if ( .not. associated(tmp)) exit
this%first => this%first%next
deallocate(tmp)
end do
this%len = 0
end subroutine clearStack
end module mod_stack
 
program main
! Empty ---------------------------------------------------------------------
use mod_stack
logical function empty(s)
type(stack_var), intent(inoutstack) :: smy_stack
integer :: i
empty = (s%size == 0 .or. .not. allocated(s%data))
real*8 :: dat
end function empty
do i = 1, 5, 1
dat = 1.0 * i
call my_stack%push(dat)
end do
do while ( .not. my_stack%isEmpty() )
print*, my_stack%pop()
end do
call my_stack%clearStack()
end program main</syntaxhighlight>
 
=={{header|Free Pascal}}==
end module stack
===Delphi adaptation===
Example taken and adapted from the Delphi entry.
<syntaxhighlight lang="pascal">program Stack;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
uses Generics.Collections;
var
lStack: TStack<Integer>;
begin
lStack := TStack<Integer>.Create;
try
lStack.Push(1);
lStack.Push(2);
lStack.Push(3);
Assert(lStack.Peek = 3); // 3 should be at the top of the stack
Write(lStack.Pop:2); // 3
Write(lStack.Pop:2); // 2
Writeln(lStack.Pop:2); // 1
Assert(lStack.Count = 0, 'Stack is not empty'); // should be empty
finally
lStack.Free;
end;
end.</syntaxhighlight>
<pre>
Output:
3 2 1
</pre>
 
===Object version from scratch===
program tstack
{{works with|Free Pascal|version 3.2.0 }}
use stack
<syntaxhighlight lang="pascal">
implicit none
PROGRAM StackObject.pas;
type(stack_var) :: s
{$IFDEF FPC}
integer :: v
{$mode objfpc}{$H+}{$J-}{$m+}{$R+}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
(*)
 
Free Pascal Compiler version 3.2.0 [2020/06/14] for x86_64
call push(s,1)
TheStack free and readable alternative at C/C++ Sidxeeds
call push(s,2)
compiles natively to almost any platform, including raSidxberry PI *
call push(s,3)
Can run independently from DELPHI / Lazarus
call push(s,4)
 
For debian Linux: apt -y install fpc
do
It contains a text IDE called fp
if (empty(s)) exit
v = pop(s)
write(*,'(a,i0)') 'Popped value off stack = ',v
end do
end program tstack</lang>
 
This is an experiment for a stack that can handle almost any
=={{header|F_Sharp|F#}}==
simple type of variable.
.NET provides a mutable stack type in <code>System.Collections.Generic.Stack</code>.
 
What happens after retrieving the variable is TBD by you.
A list-based immutable stack type could be implemented like this:
<lang fsharp>type Stack<'a> //'//(workaround for syntax highlighting problem)
(?items) =
let items = defaultArg items []
 
https://www.freepascal.org/advantage.var
member x.Push(A) = Stack(A::items)
(*)
 
member x.Pop() =
match items with
| x::xr -> (x, Stack(xr))
| [] -> failwith "Stack is empty."
 
USES
member x.IsEmpty() = items = []
Classes ,
Crt ,
Variants ;
{$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} // Use for variants
 
TYPE
// example usage
 
let anEmptyStack = Stack<int>()
Stack = OBJECT
let stack2 = anEmptyStack.Push(42)
printfn "%A" (stack2.IsEmpty())
CONST
let (x, stack3) = stack2.Pop()
printfn "%d" x
CrLf = #13#10 ;
printfn "%A" (stack3.IsEmpty())</lang>
TYPE
 
VariantArr = array of variant ;
PRIVATE
 
Ar : VariantArr ;
 
{$MACRO ON}
{$DEFINE STACKSIZE := Length ( Ar ) * Ord ( Length ( Ar ) > 0 ) }
{$DEFINE TOP := STACKSIZE - 1 * Ord ( STACKSIZE > 0 ) }
{$DEFINE SLEN := length ( Ar [ TOP ] ) * Ord ( Length ( Ar [ TOP ] ) > 0 ) }
 
FUNCTION IsEmpty : boolean ;
PROCEDURE Print ;
FUNCTION Pop : variant ;
FUNCTION Peep : variant ;
PROCEDURE Push ( item : variant ) ;
FUNCTION SecPop : variant ;
 
PUBLIC
CONSTRUCTOR Create ;
END;
 
CONSTRUCTOR Stack.Create ;
 
BEGIN
SetLength ( Ar, STACKSIZE ) ;
END;
 
FUNCTION Stack.IsEmpty : boolean ;
BEGIN
IsEmpty := ( STACKSIZE < 1 ) ;
END;
 
 
PROCEDURE Stack.Print ;
 
VAR
i : shortint ;
BEGIN
IF ( TOP < 1 ) or ( IsEmpty ) THEN
BEGIN
WriteLn ( CrLf + '<empty stack>' ) ;
EXIT ;
END;
WriteLn ( CrLf , '<top>') ;
FOR i := ( TOP ) DOWNTO 0 DO WriteLn ( Ar [ i ] ) ;
WriteLn ( '<bottom>' ) ;
END;
 
 
FUNCTION Stack.Pop : variant ;
 
BEGIN
IF IsEmpty THEN EXIT ;
Pop := Ar [ TOP ] ;
SetLength ( Ar, TOP ) ;
END;
 
 
FUNCTION Stack.Peep : variant ;
 
BEGIN
IF IsEmpty THEN EXIT ;
Peep := Ar [ TOP ] ;
END;
 
 
PROCEDURE Stack.Push ( item : variant ) ;
BEGIN
SetLength ( Ar, STACKSIZE + 1 ) ;
Ar [ TOP ] := item ;
END;
 
 
FUNCTION Stack.SecPop : variant ;
(*) Pop and Wipe (*)
BEGIN
IF IsEmpty THEN EXIT ;
SecPop := Ar [ TOP ] ;
Ar [ TOP ] := StringOfChar ( #255 , SLEN ) ;
Ar [ TOP ] := StringOfChar ( #0 , SLEN ) ;
SetLength ( Ar, TOP ) ;
END;
 
VAR
n : integer ;
r : real ;
S : string ;
So : Stack ;
 
 
BEGIN
 
So.Create ;
So.Print ;
n := 23 ;
So.Push ( n ) ;
S := '3 guesses ' ;
So.Push ( S ) ;
r := 1.23 ;
So.Push ( r ) ;
WriteLn ( 'Peep : ', So.Peep ) ;
So.Push ( 'Nice Try' ) ;
So.Print ;
WriteLn ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
WriteLn ( 'SecPop : ',So.SecPop ) ;
So.Print ;
END.
 
</syntaxhighlight>JPD 2021/07/03
 
Output:
 
<empty stack>
 
Peep : 1.23
 
<top>
 
Nice Try
 
1.23
 
3 guesses
 
23
 
<bottom>
 
SecPop : Nice Try
 
SecPop : 1.23
 
SecPop : 3 guesses
 
SecPop : 23
 
<empty stack>
 
=={{header|FreeBASIC}}==
We first use a macro to define a generic Stack type :
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' stack_rosetta.bi
' simple generic Stack type
 
#Define Stack(T) Stack_##T
 
#Macro Declare_Stack(T)
Type Stack(T)
Public:
Declare Constructor()
Declare Destructor()
Declare Property capacity As Integer
Declare Property count As Integer
Declare Property empty As Boolean
Declare Property top As T
Declare Function pop() As T
Declare Sub push(item As T)
Private:
a(any) As T
count_ As Integer = 0
Declare Function resize(size As Integer) As Integer
End Type
 
Constructor Stack(T)()
Redim a(0 To 0) '' create a default T instance for various purposes
End Constructor
 
Destructor Stack(T)()
Erase a
End Destructor
 
Property Stack(T).capacity As Integer
Return UBound(a)
End Property
Property Stack(T).count As Integer
Return count_
End Property
 
Property Stack(T).empty As Boolean
Return count_ = 0
End Property
 
Property Stack(T).top As T
If count_ > 0 Then
Return a(count_)
End If
Print "Error: Attempted to access 'top' element of an empty stack"
Return a(0) '' return default element
End Property
 
Function Stack(T).pop() As T
If count_ > 0 Then
Dim value As T = a(count_)
a(count_) = a(0) '' zero element to be removed
count_ -= 1
Return value
End If
Print "Error: Attempted to remove 'top' element of an empty stack"
Return a(0) '' return default element
End Function
 
Sub Stack(T).push(item As T)
Dim size As Integer = UBound(a)
count_ += 1
If count_ > size Then
size = resize(size)
Redim Preserve a(0 to size)
End If
a(count_) = item
End Sub
 
Function Stack(T).resize(size As Integer) As Integer
If size = 0 Then
size = 4
ElseIf size <= 32 Then
size = 2 * size
Else
size += 32
End If
Return size
End Function
#EndMacro</syntaxhighlight>
 
We now use this type to create a Stack of Dog instances :
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "stack_rosetta.bi"
 
Type Dog
name As String
age As Integer
Declare Constructor
Declare Constructor(name_ As string, age_ As integer)
Declare Operator Cast() As String
end type
 
Constructor Dog '' default constructor
End Constructor
 
Constructor Dog(name_ As String, age_ As Integer)
name = name_
age = age_
End Constructor
 
Operator Dog.Cast() As String
Return "[" + name + ", " + Str(age) + "]"
End Operator
 
Declare_Stack(Dog) '' expand Stack type for Dog instances
 
Dim dogStack As Stack(Dog)
 
Var cerberus = Dog("Cerberus", 10)
Var rover = Dog("Rover", 3)
Var puppy = Dog("Puppy", 0)
With dogStack '' push these Dog instances onto the stack
.push(cerberus)
.push(rover)
.push(puppy)
End With
Print "Number of dogs on the stack :" ; dogStack.count
Print "Capacity of dog stack :" ; dogStack.capacity
Print "Top dog : "; dogStack.top
dogStack.pop()
Print "Top dog now : "; dogStack.top
Print "Number of dogs on the stack :" ; dogStack.count
dogStack.pop()
Print "Top dog now : "; dogStack.top
Print "Number of dogs on the stack :" ; dogStack.count
Print "Is stack empty now : "; dogStack.empty
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
Number of dogs on the stack : 3
Capacity of dog stack : 4
Top dog : [Puppy, 0]
Top dog now : [Rover, 3]
Number of dogs on the stack : 2
Top dog now : [Cerberus, 10]
Number of dogs on the stack : 1
Is stack empty now : false
</pre>
 
=={{header|Frink}}==
Frink's <CODE>array</CODE> class has all of the methods to make it usable as a stack or a deque. The methods are called <CODE><I>array</I>.push[<I>x</I>]</CODE>, <CODE><I>array</I>.pop[]</CODE>, and <CODE><I>array</I>.isEmpty[]</CODE>
<syntaxhighlight lang="frink">a = new array
a.push[1]
a.push[2]
a.peek[]
while ! a.isEmpty[]
println[a.pop[]]</syntaxhighlight>
 
=={{header|Genie}}==
<syntaxhighlight lang="genie">[indent=4]
/*
Stack, in Genie, with GLib double ended Queues
valac stack.gs
*/
init
var stack = new Queue of int()
 
// push
stack.push_tail(2)
stack.push_tail(1)
 
// pop (and peek at top)
print stack.pop_tail().to_string()
print stack.peek_tail().to_string()
 
// empty
print "stack size before clear: " + stack.get_length().to_string()
stack.clear()
print "After clear, stack.is_empty(): " + stack.is_empty().to_string()</syntaxhighlight>
 
{{out}}
<pre>prompt$ valac stack.gs
prompt$ ./stack
1
2
stack size before clear: 1
After clear, stack.is_empty(): true</pre>
 
=={{header|Go}}==
Go slices make excellent stacks without defining any extra types, functions, or methods. For example, to keep a stack of integers, simply declare one as,
<syntaxhighlight lang ="go">var intStack []int</langsyntaxhighlight>
Use the built in append function to push numbers on the stack:
<langsyntaxhighlight lang="go">intStack = append(intStack, 7)</langsyntaxhighlight>
Use a slice expression with the built in len function to pop from the stack:
<langsyntaxhighlight lang="go">popped, intStack = intStack[len(intStack)-1], intStack[:len(intStack)-1]</langsyntaxhighlight>
The test for an empty stack:
<langsyntaxhighlight lang="go">len(intStack) == 0</langsyntaxhighlight>
And to peek at the top of the stack:
<syntaxhighlight lang ="go">intStack[len(intStack)-1]</langsyntaxhighlight>
It is idiomatic Go to use primitive language features where they are sufficient, and define helper functions or types and methods only as they make sense for a particular situation. Below is an example using a type with methods and idiomatic "ok" return values to avoid panics. It is only an example of something that might make sense in some situation.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,747 ⟶ 3,485:
fmt.Println("nothing to pop")
}
}</langsyntaxhighlight>
{{out}}
Output:
<pre>
new stack: []
Line 1,757 ⟶ 3,495:
top value: four
four popped. stack: [3]
</pre>
 
=={{header|GDScript}}==
In GDScript there is built-in Array class, that implements either 'push', 'pop', 'top' and 'empty' methods. Method names are:
<ul>
<li>push -> push_back</li>
<li>pop -> pop_back</li>
<li>top -> back</li>
<li>empty -> is_empty</li>
</ul>
<syntaxhighlight lang="gdscript">
extends Node2D
 
func _ready() -> void:
# Empty stack creation.
var stack : Array = []
# In Godot 4.2.1 nothing happens here.
stack.pop_back()
if stack.is_empty():
print("Stack is empty.")
stack.push_back(3)
stack.push_back("Value")
stack.push_back(1.5e32)
print(stack)
print("Last element is: " + str(stack.back()))
stack.pop_back()
print(stack)
print("Last element is: " + str(stack.back()))
if not stack.is_empty():
print("Stack is not empty.")
return
</syntaxhighlight>
{{out}}
<pre>
Stack is empty.
[3, "Value", 149999999999999999042044051849216]
Last element is: 149999999999999999042044051849216
[3, "Value"]
Last element is: Value
Stack is not empty.
</pre>
 
Line 1,763 ⟶ 3,546:
 
Of course, these stack semantics are not ''exclusive''. Elements of the list can still be accessed and manipulated in myriads of other ways.
 
<lang groovy>def stack = []
If you need exclusive stack semantics, you can use the <code>java.util.Stack</code> class, as demonstrated in the [[Stack#Java|Java]] example.
 
<syntaxhighlight lang="groovy">def stack = []
assert stack.empty
 
Line 1,799 ⟶ 3,585:
assert stack.empty
 
try { stack.pop() } catch (NoSuchElementException e) { println e.message }</langsyntaxhighlight>
 
{{out}}
Output:
<pre>[55, 21, kittens]
[55, 21]
Line 1,812 ⟶ 3,598:
=={{header|Haskell}}==
The Haskell solution is trivial, using a list. Note that <code>pop</code> returns both the element and the changed stack, to remain purely functional.
<langsyntaxhighlight lang="haskell">type Stack a = [a]
 
create :: Stack a
Line 1,829 ⟶ 3,615:
peek :: Stack a -> a
peek [] = error "Stack empty"
peek (x:_) = x</langsyntaxhighlight>
We can make a stack that can be destructively popped by hiding the list inside a <code>State</code> monad.
<langsyntaxhighlight lang="haskell">import Control.Monad.State
 
type Stack a b = State [a] b
Line 1,852 ⟶ 3,638:
 
nonEmpty :: Stack a ()
nonEmpty = empty >>= flip when (fail "Stack empty")</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Stacks (and double ended queues) are built into Icon and Unicon as part of normal list access. In addition to 'push' and 'pop', there are the functions 'put', 'get' (alias for pop), 'pull', list element addressing, and list sectioning (like sub-strings). Unicon extended 'insert' and 'delete' to work with lists. The programmer is free to use any or all of the list processing functions on any problem. The following illustrates typical stack usage:
Unicon extended 'insert' and 'delete' to work with lists.
<lang Icon>procedure main()
The programmer is free to use any or all of the list processing functions on any problem.
The following illustrates typical stack usage:
<syntaxhighlight lang="icon">procedure main()
stack := [] # new empty stack
push(stack,1) # add item
Line 1,871 ⟶ 3,660:
procedure top(x) #: return top element w/o changing stack
return x[1] # in practice, just use x[1]
end</langsyntaxhighlight>
 
=={{header|Io}}==
aside from using built-in lists, a stack can be created using nodes like so:
<langsyntaxhighlight lang="io">Node := Object clone do(
next := nil
obj := nil
Line 1,895 ⟶ 3,684:
self node = nn
)
)</langsyntaxhighlight>
 
=={{header|Ioke}}==
<langsyntaxhighlight lang="ioke">Stack = Origin mimic do(
initialize = method(@elements = [])
pop = method(@elements pop!)
empty = method(@elements empty?)
push = method(element, @elements push!(element))
)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 LET N=255 ! Size of stack
110 NUMERIC STACK(1 TO N)
120 LET PTR=1
130 DEF PUSH(X)
140 IF PTR>N THEN
150 PRINT "Stack is full.":STOP
160 ELSE
170 LET STACK(PTR)=X:LET PTR=PTR+1
180 END IF
190 END DEF
200 DEF POP
210 IF PTR=1 THEN
220 PRINT "Stack is empty.":STOP
230 ELSE
240 LET PTR=PTR-1:LET POP=STACK(PTR)
250 END IF
260 END DEF
270 DEF EMPTY
280 LET PTR=1
290 END DEF
300 DEF TOP=STACK(PTR-1)
310 CALL PUSH(3):CALL PUSH(5)
320 PRINT POP+POP</syntaxhighlight>
 
=={{header|J}}==
<langsyntaxhighlight Jlang="j">stack=: ''
push=: monad def '0$stack=:stack,y'
pop=: monad def 'r[ stack=:}:stack[ r=.{:stack'
empty=: monad def '0=#stack'</langsyntaxhighlight>
Example use:
<langsyntaxhighlight Jlang="j"> push 9
 
pop ''
9
empty ''
1</langsyntaxhighlight>
pop and empty ignore their arguments. In this implementation. push returns an empty list.
 
=={{header|Java}}==
The collections framework includes a Stack class. Let's test it:
<langsyntaxhighlight Javalang="java">import java.util.Stack;
 
public class StackTest {
Line 1,941 ⟶ 3,755:
stack.pop();
}
}</langsyntaxhighlight>
{{out}}
<pre>New stack empty? true
Line 1,953 ⟶ 3,767:
 
Alternatively, you might implement a stack yourself...
<langsyntaxhighlight lang="java">public class Stack{
private Node first = null;
public boolean isEmpty(){
Line 1,981 ⟶ 3,795:
}
}
}</langsyntaxhighlight>
{{works with|Java|1.5}}
<langsyntaxhighlight lang="java5">public class Stack<T>{
private Node first = null;
public boolean isEmpty(){
Line 2,011 ⟶ 3,825:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
The built-in Array class already has stack primitives.
<langsyntaxhighlight lang="javascript">var stack = [];
stack.push(1)
stack.push(2,3);
print(stack.pop()); // 3
print(stack.length); // 2, stack empty if 0</langsyntaxhighlight>
Here's a constructor that wraps the array:
<langsyntaxhighlight lang="javascript">function Stack() {
this.data = new Array();
 
Line 2,027 ⟶ 3,841:
this.pop = function() {return this.data.pop()}
this.empty = function() {return this.data.length == 0}
this.peek = function() {return this.data[0this.data.length - 1]}
}</langsyntaxhighlight>
Here's an example using the revealing module pattern instead of prototypes.
<syntaxhighlight lang="javascript">
function makeStack() {
var stack = [];
 
var popStack = function () {
return stack.pop();
};
var pushStack = function () {
return stack.push.apply(stack, arguments);
};
var isEmpty = function () {
return stack.length === 0;
};
var peekStack = function () {
return stack[stack.length-1];
};
return {
pop: popStack,
push: pushStack,
isEmpty: isEmpty,
peek: peekStack,
top: peekStack
};
}
</syntaxhighlight>
 
=={{header|Jsish}}==
From Javascript entry. Being ECMAScript, Jsi supports stack primitives as part of the Array methods.
<syntaxhighlight lang="javascript">/* Stack, is Jsish */
var stack = [];
puts('depth:', stack.length);
 
stack.push(42);
stack.push('abc');
puts('depth:', stack.length);
 
puts('popped:', stack.pop());
if (stack.length) printf('not '); printf('empty\n');
puts('top:', stack[stack.length-1]);
puts('popped:', stack.pop());
if (stack.length) printf('not '); printf('empty\n');
 
puts('depth:', stack.length);</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish stack.jsi
depth: 0
depth: 2
popped: abc
not empty
top: 42
popped: 42
empty
depth: 0</pre>
 
=={{header|jq}}==
For most purposes, jq's arrays can be used for stacks if needed, without much further ado.
However, since the present task requires the definition of special stack-oriented operations,
we shall start with the following definitions:
<syntaxhighlight lang=jq>
# create a Stack
def Stack: {stack: []};
 
# check an object is a Stack
def isStack:
type == "object" and has("stack") and (.stack|type) == "array";
 
def pop:
if .stack|length == 0 then "pop: stack is empty" | error
else {stack: .stack[1:], item: .stack[0]]
end;
 
def push($x):
.stack = [$x] + .stack | .item = null;
 
def size:
.stack | length;
 
def isEmpty:
size == 0;
</syntaxhighlight>
 
Depending on context, additional code to check for or to enforce
type discipline could be added, but is omitted for simplicity here.
If using the C implementation of jq, the function names could also
be prefixed with "Stack::" to distinguish them as stack-oriented
operations.
 
For some purposes, this approach may be sufficient, but it can easily
become cumbersome if a sequence of operations must be performed
while also producing outputs that reflect intermediate states.
 
Suppose for example that we wish to create a stack, push some value,
and then pop the stack, obtaining the popped value as the final
result. This could be accomplished by the pipe:
<syntaxhighlight lang=jq>
Stack | push(3) | pop | .item
</syntaxhighlight>
 
Now suppose we also wish to record the size of the stack after each of these three operations.
One way to do this would be to write:
<syntaxhighlight lang=jq>
Stack
| size, (push(3)
| size, (pop
| size, .item ))
</syntaxhighlight>
 
Unfortunately this approach is error-prone and can quickly become tedious, so
we introduce an "observer" function that can "observe" intermediate states following any operation.
With observer/2 as defined below, we can instead write:
<syntaxhighlight lang=jq>
null
| observe(Stack; size)
| observe(push(3); size)
| observe(pop; size)
| .emit, item
</syntaxhighlight>
 
The idea is that each call to `observe` updates the "emit" slot, so that
all the accumulated messages are available at any point in the pipeline.
 
<syntaxhighlight lang=jq>
# Input: an object
# Output: the updated object with .emit filled in from `update|emit`.
# `emit` may produce a stream of values, which need not be strings.
def observe(update; emit):
def s(stream): reduce stream as $_ (null;
if $_ == null then .
elif . == null then "\($_)"
else . + "\n\($_)"
end);
.emit as $x
| update
| .emit = s($x // null, emit);
</syntaxhighlight>
 
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
The built-in <code>Array</code> class already has efficient (linear amortized time) stack primitives.
<langsyntaxhighlight lang="julia">stack = {}Int[] # []
@show push!(stack, 1) # [1]
@show push!(stack, 2) # [1, 2]
@show push!(stack, 3) # [1, 2, 3]
println(@show pop!(stack)) # 3
println(@show length(stack)) # 2
@show empty!(stack) # []
println(length@show isempty(stack)) # 0true</langsyntaxhighlight>
 
=={{header|LassoK}}==
<syntaxhighlight lang="k">stack:()
Lasso Arrays natively supports push and pop.
push:{stack::x,stack}
pop:{r:*stack;stack::1_ stack;r}
empty:{0=#stack}
 
/example:
<lang Lasso>local(a) = array
stack:()
push 3
stack
,3
push 5
stack
5 3
pop[]
5
stack
,3
empty[]
0
pop[]
3
stack
!0
empty[]
1
</syntaxhighlight>
 
=={{header|Kotlin}}==
#a->push('a')
Rather than use the java.util.Stack<E> class, we will write our own simple Stack<E> class for this task:
#a->push('b')
<syntaxhighlight lang="scala">// version 1.1.2
#a->push('c')
 
class Stack<E> {
#a->pop // c
private val data = mutableListOf<E>()
#a->pop // b
 
#a->pop // a
val size get() = data.size
#a->pop // null</lang>
 
val empty get() = size == 0
 
fun push(element: E) = data.add(element)
 
fun pop(): E {
if (empty) throw RuntimeException("Can't pop elements from an empty stack")
return data.removeAt(data.lastIndex)
}
 
val top: E
get() {
if (empty) throw RuntimeException("Empty stack can't have a top element")
return data.last()
}
 
fun clear() = data.clear()
 
override fun toString() = data.toString()
}
 
fun main(args: Array<String>) {
val s = Stack<Int>()
(1..5).forEach { s.push(it) }
println(s)
println("Size of stack = ${s.size}")
print("Popping: ")
(1..3).forEach { print("${s.pop()} ") }
println("\nRemaining on stack: $s")
println("Top element is now ${s.top}")
s.clear()
println("After clearing, stack is ${if(s.empty) "empty" else "not empty"}")
try {
s.pop()
}
catch (e: Exception) {
println(e.message)
}
}</syntaxhighlight>
 
{{out}}
<pre>
[1, 2, 3, 4, 5]
Size of stack = 5
Popping: 5 4 3
Remaining on stack: [1, 2]
Top element is now 2
After clearing, stack is empty
Can't pop elements from an empty stack
</pre>
 
=={{header|Lambdatalk}}==
The APIs of stacks and queues are built on lambdatalk array primitives, [A.new, A.disp, A.join, A.split, A.array?, A.null?, A.empty?, A.in?, A.equal?, A.length, A.get, A.first, A.last, A.rest, A.slice, A.duplicate, A.reverse, A.concat, A.map, A.set!, A.addlast!, A.sublast!, A.addfirst!, A.subfirst!, A.reverse!, A.sort!, A.swap!, A.lib]. Note that the [A.addlast!, A.sublast!, A.addfirst!, A.subfirst!] primitives are the standard [push!, shift!, pop!, unshift!] ones.
 
<syntaxhighlight lang="scheme">
{def stack.add
{lambda {:v :s}
{let { {_ {A.addfirst! :v :s}}}
} ok}}
-> stack.add
 
{def stack.get
{lambda {:s}
{let { {:v {A.first :s}}
{_ {A.subfirst! :s}}
} :v}}}
-> stack.get
 
{def stack.peek
{lambda {:s}
{A.first :s}}}
-> stack.peek
 
{def stack.empty?
{lambda {:s}
{A.empty? :s}}}
-> stack.empty?
 
{def S {A.new}} -> S []
{stack.add 1 {S}} -> ok [1]
{stack.add 2 {S}} -> ok [2,1]
{stack.add 3 {S}} -> ok [3,2,1]
{stack.empty? {S}} -> false
{stack.get {S}} -> 3 [2,1]
{stack.add 4 {S}} -> ok [4,2,1]
{stack.peek {S}} -> 4 [4,2,1]
{stack.get {S}} -> 4 [2,1]
{stack.get {S}} -> 2 [1]
{stack.get {S}} -> 1 []
{stack.get {S}} -> undefined
{stack.empty? {S}} -> true
 
</syntaxhighlight>
 
=={{header|lang5}}==
<langsyntaxhighlight lang="lang5">: cr "\n" . ;
: empty? dup execute length if 0 else -1 then swap drop ;
: pop dup execute length 1 - extract swap drop ;
Line 2,069 ⟶ 4,140:
pop . s. cr # 2 [ 1 ]
pop drop
empty? . # -1</langsyntaxhighlight>
 
=={{header|Lasso}}==
Lasso Arrays natively supports push and pop.
 
<syntaxhighlight lang="lasso">local(a) = array
 
#a->push('a')
#a->push('b')
#a->push('c')
 
#a->pop // c
#a->pop // b
#a->pop // a
#a->pop // null</syntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
global stack$
stack$=""
Line 2,111 ⟶ 4,196:
empty =(stack$="")
end function
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">-- parent script "Stack"
 
property _tos
 
on push (me, data)
me._tos = [#data:data, #next:me._tos]
end
 
on pop (me)
if voidP(me._tos) then return VOID
data = me._tos.data
me._tos = me._tos.next
return data
end
 
on peek (me)
if voidP(me._tos) then return VOID
return me._tos.data
end
 
on empty (me)
return voidP(me.peek())
end</syntaxhighlight>
 
=={{header|Logo}}==
[[UCB Logo]] has built-in methods for treating lists as stacks. Since they are destructive, they take the name of the stack rather than the list itself.
<langsyntaxhighlight lang="logo">make "stack []
push "stack 1
push "stack 2
push "stack 3
print pop "stack ; 3
print empty? :stack ; false</langsyntaxhighlight>
 
=={{header|Logtalk}}==
A stack can be trivially represented using the built-in representation for lists:
<langsyntaxhighlight lang="logtalk">
:- object(stack).
 
Line 2,137 ⟶ 4,247:
 
:- end_object.
</syntaxhighlight>
</lang>
 
=={{header|LOLCODE}}==
{{trans|UNIX Shell}}
<syntaxhighlight lang="lolcode">HAI 2.3
HOW IZ I Init YR Stak
Stak HAS A Length ITZ 0
IF U SAY SO
 
HOW IZ I Push YR Stak AN YR Value
Stak HAS A SRS Stak'Z Length ITZ Value
Stak'Z Length R SUM OF Stak'Z Length AN 1
IF U SAY SO
 
HOW IZ I Top YR Stak
FOUND YR Stak'Z SRS DIFF OF Stak'Z Length AN 1
IF U SAY SO
 
HOW IZ I Pop YR Stak
I HAS A Top ITZ I IZ Top YR Stak MKAY
Stak'Z Length R DIFF OF Stak'Z Length AN 1
FOUND YR Top
IF U SAY SO
 
HOW IZ I Empty YR Stak
FOUND YR BOTH SAEM 0 AN Stak'Z Length
IF U SAY SO
 
I HAS A Stak ITZ A BUKKIT
I IZ Init YR Stak MKAY
I IZ Push YR Stak AN YR "Fred" MKAY
I IZ Push YR Stak AN YR "Wilma" MKAY
I IZ Push YR Stak AN YR "Betty" MKAY
I IZ Push YR Stak AN YR "Barney" MKAY
 
IM IN YR Loop UPPIN YR Dummy TIL I IZ Empty YR Stak MKAY
VISIBLE I IZ Pop YR Stak MKAY
IM OUTTA YR Loop
 
KTHXBYE</syntaxhighlight>
 
{{Out}}
<pre>Barney
Betty
Wilma
Fred</pre>
 
=={{header|Lua}}==
Tables have stack primitives by default:
<langsyntaxhighlight lang="lua">stack = {}
table.insert(stack,3)
print(table.remove(stack)) --> 3</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
A Stack object can be used as LIFO or FIFO. Push statement push to top of stack. Read pop a value to a variable from top of stack. StackItem(1) read top item without modified stack. Data statement append items to bottom.
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
a=Stack
Stack a {
Push 100, 200, 300
}
Print StackItem(a, 1)=300
Stack a {
Print StackItem(1)=300
While not empty {
Read N
Print N
}
}
}
Checkit
</syntaxhighlight>
 
Every module and function has a "current" stack. Number is a read only variable, which pop a value from current stack (or raise error if not number is in top of stack).
 
User functions get a new stack, and drop it at return. Modules take parent stack, and return stack to parent. So a Module can return values too. In M2000 a call happen without checkig signatures (except for special events calls). We have to leave stack at a proper state, when return from a module.
Return/Execution stack is hidden and different from stack of values.
 
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Read a, b
Print a, b
}
\\ add parameters in a FIFO, and this FIFO merged to current stack
Push 100
Checkit 10, 20
Print StackItem(1)=100
Module Checkit {
Read a, b
Print a=20, b=100
}
Checkit 20
 
Function alfa {
k=0
n=0
while not empty {
k+=number
n++
}
if n=0 then Error "No parameters found"
=k/n
}
 
Print alfa(1,2,3,4)=2.5
 
</syntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">with(stack): # load the package, to allow use of short command names
 
s := stack:-new(a, b):
Line 2,159 ⟶ 4,368:
empty(s);
pop(s);
empty(s);</langsyntaxhighlight>
{{out}}
Output:
<pre> c
 
Line 2,173 ⟶ 4,382:
true</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">EmptyQ[a_] := If[Length[a] == 0, True, False]
SetAttributes[Push, HoldAll];[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete];
Line 2,187 ⟶ 4,396:
->4
Peek[stack]
->3</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Here is a simple implementation of a stack, that works in Matlab and Octave. It is closely related to the queue/fifo example.
<langsyntaxhighlight lang="matlab">mystack = {};
% push
Line 2,203 ⟶ 4,412:
 
% empty
isempty(mystack)</langsyntaxhighlight>
Below is another solution, that encapsulates the fifo within the object-orientated "class" elements supported by Matlab. The given implementation is exactly the same as the MATLAB FIFO example, except that the "push()" function is modified to add stuff to the end of the queue instead of the beginning. This is a naive implementation, for rigorous applications this should be modified to initialize the LIFO to a buffered size, so that the "pop()" and "push()" functions don't resize the cell array that stores the LIFO's elements, every time they are called.
 
To use this implementation you must save this code in a MATLAB script file named "LIFOQueue.m" which must be saved in a folder named @LIFOQueue in your MATLAB directory.
<langsyntaxhighlight MATLABlang="matlab">%This class impliments a standard LIFO queue.
classdef LIFOQueue
Line 2,288 ⟶ 4,497:
end %methods
end</langsyntaxhighlight>
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> myLIFO = LIFOQueue(1,'fish',2,'fish','red fish','blue fish')
myLIFO =
Line 2,319 ⟶ 4,528:
ans =
 
0</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* lists can be used as stacks; Maxima provides pop and push */
 
load(basic)$
Line 2,332 ⟶ 4,541:
 
emptyp(a);
length(a);</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 2,338 ⟶ 4,547:
Efficient, generic stacks are provided as part of the standard library in Mercury. For sake of illustration, here is how a simple stack could be implemented.
 
<langsyntaxhighlight lang="mercury">:- module sstack.
 
:- interface.
Line 2,370 ⟶ 4,579:
!:Stack = sstack(Elems).
 
:- end_module sstack.</langsyntaxhighlight>
 
It should be noted that this is purely an illustrative example of a very simple stack.
It should be noted that this is purely an illustrative example of a very simple stack. A real implementation would have predicate (:- pred) versions of the functions (:- func), for example, for consistency's sake with either the functions implemented in terms of the predicates or vice versa. [http://www.mercurylang.org/information/doc-release/mercury_library/stack.html#stack The real library implementation] also features more functionality including both semi-deterministic and deterministic versions of some functions/predicates as well as the ability to push a list of values in one operation.
A real implementation would have predicate (:- pred) versions of the functions (:- func), for example, for consistency's sake with either the functions implemented in terms of the predicates or vice versa. [http://www.mercurylang.org/information/doc-release/mercury_library/stack.html#stack The real library implementation] also features more functionality including both semi-deterministic and deterministic versions of some functions/predicates as well as the ability to push a list of values in one operation.
 
Some of the implementation decisions above need an explanation.
Some of the implementation decisions above need an explanation. new/0 and push/2 were implemented as functions both for pedagogical reasons (a desire to show function syntax) and because they are a natural fit for functional thought: 0 or more inputs, one output, deterministic. is_empty/1 was implemented as a predicate because it's a single, simple succeed/fail test which is precisely what a predicate is in logic. pop/3 was implemented as a predicate because it has two outputs (the element and the new stack) ''and'' because it is semi-deterministic (it will fail if the stack is empty).
new/0 and push/2 were implemented as functions both for pedagogical reasons (a desire to show function syntax) and because they are a natural fit for functional thought: 0 or more inputs, one output, deterministic.
is_empty/1 was implemented as a predicate because it's a single, simple succeed/fail test which is precisely what a predicate is in logic.
pop/3 was implemented as a predicate because it has two outputs (the element and the new stack) ''and'' because it is semi-deterministic (it will fail if the stack is empty).
 
Note also that while pop/3 has three parameters, the function implementation looks like it has two. This is because the !Stack "parameter" is actually a ''pair'' of parameters using Mercury's state variable notation. !Stack is, in effect, two variables: !.Stack and !:Stack, input and output respectively. Using state variable notation here is a bit of overkill but again was brought in for pedagogical reasons to show the syntax.
 
=={{header|MIPS Assembly}}==
 
<syntaxhighlight lang="mips">addi sp,sp,-4
sw t0,0(sp) ;push
 
lw t0,0(sp)
addi sp,sp,4 ;pop
 
lw t0,0(sp) ;top</syntaxhighlight>
 
"Empty" requires you to know the starting value of <code>SP</code>. Since it's hardware-dependent, there's no one answer for this part of the task.
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">// Note in Miniscript, a value of zero is false,
// and any other number is true.
// therefore the .len function works as the inverse of a .empty function
stack = [2, 4, 6]
stack.push 8
print "Stack is " + stack
print "Adding '9' to stack " + stack.push(9)
print "Top of stack is " + stack.pop
print "Stack is " + stack
if stack.len then
print "Stack is not empty"
else
print "Stack is empty"
end if</syntaxhighlight>
{{out}}
<pre>
Stack is [2, 4, 6, 8]
Adding '9' to stack [2, 4, 6, 8, 9]
Top of stack is 9
Stack is [2, 4, 6, 8]
Stack is not empty
</pre>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">class Stack
declare internalList
 
// constructor
def Stack()
internalList = list()
end
 
def push(val)
internalList.append(val)
end
 
def pop()
val = internalList[int(len($internalList) - 1)]
internalList.remove(val)
 
return val
end
 
def empty()
return len(internalList) = 0
end
end</syntaxhighlight>
 
=={{header|Nemerle}}==
Mutable stacks are available in <tt>System.Collections</tt>, <tt>System.Collections.Generic</tt> and <tt>Nemerle.Collections</tt> depending on what functionality beyond the basics you want. An immutable stack could be implemented fairly easily, as, for example, this quick and dirty list based implementation.
<langsyntaxhighlight Nemerlelang="nemerle">public class Stack[T]
{
private stack : list[T];
Line 2,413 ⟶ 4,687:
stack.Length == 0
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* NetRexx ************************************************************
* 13.08.2013 Walter Pachl translated from REXX version 2
**********************************************************************/
Line 2,457 ⟶ 4,731:
 
method empty(stk) static
Return stk[0]=0</langsyntaxhighlight>
{{out}}
Output:
<pre>
123 from push
Line 2,468 ⟶ 4,742:
</pre>
 
=={{header|NimrodNim}}==
In Nim, the sequences offer all the functionalities of a stack. Procedure <code>add</code> appends an item at the end, procedure <code>pop</code> returns the last element and removes it from the sequence. And it’s easy to check if if the sequence is empty with the procedure <code>len</code> which returns its length.
<lang nimrod>
import math
 
If we want a stack type limited to the four or five functions of the task, it is possible to define a distinct generic type <code>Stack[T]</code> derived from <code>seq[T]</code>. The code will be typically as follows. Note that we have defined a procedure <code>top</code> to get the value of the top item, another <code>mtop</code> to get a mutable reference to the top item and also a procedure <code>mtop=</code> to assign directly a value to the top item.
type
EStackEmpty = object of E_Base
 
<syntaxhighlight lang="nim">type Stack[T] = distinct seq[T]
TStack* [A] = object
data: seq[A]
count: int
 
procfunc initStack*[AT](initialSize = 32): TStackStack[AT] =
assert isPowerOfTwoStack[T](newSeq[T](initialSize))
result.count = 0
newSeq(result.data,initialSize)
 
procfunc cap*isEmpty[AT] (sstack: TStackStack[AT]): intbool =
seq[T](stack).len == 0
result = s.data.len
 
procfunc len*push[AT](stack: TStackvar Stack[AT]); item: intsink T) =
result = seq[T](stack).countadd(item)
 
procfunc push*pop[AT](sstack: var TStackStack[AT], item): A)T =
if sstack.count == s.data.lenisEmpty:
raise newException(IndexDefect, "stack is empty.")
# not enough room, make container bigger
seq[T](stack).pop()
var d: Seq[A]
newSeq(d,s.len * 2)
for i in 0 .. s.data.len - 1:
shallowCopy(d[i],s.data[i])
shallowCopy(s.data,d)
s.data[s.count] = item
inc(s.count)
 
func top[T](stack: Stack[T]): T =
proc pop*[A](s: var TStack[A]): A {.raises: [EStackEmpty].}=
if sstack.count == 0isEmpty:
raise newException(EStackEmptyIndexDefect,"the "stack is empty.")
seq[T](stack)[^1]
dec(s.count)
result = s.data[s.count]
 
procfunc top*mtop[AT](sstack: TStackvar Stack[AT]): Avar =T =
if stack.isEmpty:
result = s.data[s.count - 1]
raise newException(IndexDefect, "stack is empty.")
seq[T](stack)[^1]
 
procfunc isEmpty*`mtop=`[AT](sstack: var TStackStack[AT]); value: boolT) =
if stack.isEmpty:
return s.count == 0
raise newException(IndexDefect, "stack is empty.")
seq[T](stack)[^1] = value
 
#Tests
when isMainModule:
var stk: TStack[char] = initStack[char](4)
stk.push('a')
stk.push('b')
stk.push('c')
stk.push('d')
assert(stk.count == 4)
assert(stk.data.len == 4)
stk.push('e')
assert(stk.cap == 8)
assert(stk.top == 'e')
 
var s = initStack[int]()
s.push 2
discard stk.pop
discardecho stks.pop
s.push 3
discard stk.pop
discardecho stks.poptop
s.mtop += 1
assert(stk.isEmpty == false)
discardecho stks.poptop
assert(stks.isEmptymtop == true)5
echo s.top</syntaxhighlight>
 
{{out}}
try:
<pre>2
discard stk.pop
3
except:
4
let
5</pre>
e = getCurrentException()
 
msg = getCurrentExceptionMsg()
=={{header|Oberon-2}}==
echo "Exception: [[", repr(e), "]] msg: ", msg
{{Works with|oo2c version 2}}
<syntaxhighlight lang="oberon2">
MODULE Stacks;
IMPORT
Object,
Object:Boxed,
Out := NPCT:Console;
 
TYPE
Pool(E: Object.Object) = POINTER TO ARRAY OF E;
Stack*(E: Object.Object) = POINTER TO StackDesc(E);
StackDesc*(E: Object.Object) = RECORD
pool: Pool(E);
cap-,top: LONGINT;
END;
 
PROCEDURE (s: Stack(E)) INIT*(cap: LONGINT);
BEGIN
NEW(s.pool,cap);s.cap := cap;s.top := -1
END INIT;
 
PROCEDURE (s: Stack(E)) Top*(): E;
BEGIN
RETURN s.pool[s.top]
END Top;
 
PROCEDURE (s: Stack(E)) Push*(e: E);
BEGIN
INC(s.top);
ASSERT(s.top < s.cap);
s.pool[s.top] := e;
END Push;
 
PROCEDURE (s: Stack(E)) Pop*(): E;
VAR
resp: E;
BEGIN
ASSERT(s.top >= 0);
resp := s.pool[s.top];DEC(s.top);
RETURN resp
END Pop;
 
PROCEDURE (s: Stack(E)) IsEmpty(): BOOLEAN;
BEGIN
RETURN s.top < 0
END IsEmpty;
 
PROCEDURE (s: Stack(E)) Size*(): LONGINT;
BEGIN
RETURN s.top + 1
END Size;
 
PROCEDURE Test;
VAR
s: Stack(Boxed.LongInt);
BEGIN
s := NEW(Stack(Boxed.LongInt),100);
s.Push(NEW(Boxed.LongInt,10));
s.Push(NEW(Boxed.LongInt,100));
Out.String("size: ");Out.Int(s.Size(),0);Out.Ln;
Out.String("pop: ");Out.Object(s.Pop());Out.Ln;
Out.String("top: ");Out.Object(s.Top());Out.Ln;
Out.String("size: ");Out.Int(s.Size(),0);Out.Ln
END Test;
BEGIN
Test
END Stacks.
</syntaxhighlight>
{{out}}
<pre>
size: 2
pop: 100
top: 10
size: 1
</pre>
{{works with|AOS}}
<syntaxhighlight lang="oberon2">
MODULE Stacks; (** AUTHOR ""; PURPOSE ""; *)
 
IMPORT
Out := KernelLog;
 
TYPE
Object = OBJECT
END Object;
Stack* = OBJECT
VAR
top-,capacity-: LONGINT;
pool: POINTER TO ARRAY OF Object;
PROCEDURE & InitStack*(capacity: LONGINT);
BEGIN
SELF.capacity := capacity;
SELF.top := -1;
NEW(SELF.pool,capacity)
END InitStack;
PROCEDURE Push*(a:Object);
BEGIN
INC(SELF.top);
ASSERT(SELF.top < SELF.capacity,100);
SELF.pool[SELF.top] := a
END Push;
PROCEDURE Pop*(): Object;
VAR
r: Object;
BEGIN
ASSERT(SELF.top >= 0);
r := SELF.pool[SELF.top];
DEC(SELF.top);RETURN r
END Pop;
PROCEDURE Top*(): Object;
BEGIN
ASSERT(SELF.top >= 0);
RETURN SELF.pool[SELF.top]
END Top;
PROCEDURE IsEmpty*(): BOOLEAN;
BEGIN
RETURN SELF.top < 0
END IsEmpty;
END Stack;
BoxedInt = OBJECT
(Object)
VAR
val-: LONGINT;
 
PROCEDURE & InitBoxedInt*(CONST val: LONGINT);
BEGIN
SELF.val := val
END InitBoxedInt;
 
END BoxedInt;
 
PROCEDURE Test*;
VAR
s: Stack;
bi: BoxedInt;
obj: Object;
BEGIN
NEW(s,10); (* A new stack of ten objects *)
NEW(bi,100);s.Push(bi);
NEW(bi,102);s.Push(bi);
NEW(bi,104);s.Push(bi);
Out.Ln;
Out.String("Capacity:> ");Out.Int(s.capacity,0);Out.Ln;
Out.String("Size:> ");Out.Int(s.top + 1,0);Out.Ln;
obj := s.Pop(); obj := s.Pop();
WITH obj: BoxedInt DO
Out.String("obj:> ");Out.Int(obj.val,0);Out.Ln
ELSE
Out.String("Unknown object...");Out.Ln;
END (* with *)
END Test;
END Stacks.
</syntaxhighlight>
{{out}}
<pre>
Capacity:> 10
Size:> 3
obj:> 102
</pre>
 
</lang>
=={{header|Objeck}}==
Class library support for Stack/IntStack/FloatStack
<langsyntaxhighlight lang="objeck">stack := IntStack->New();
stack->Push(13);
stack->Push(7);
(stack->Pop() + stack->Pop())->PrintLine();
stack->IsEmpty()->PrintLine();</langsyntaxhighlight>
 
=={{header|Objective-C}}==
Using a NSMutableArray:
<langsyntaxhighlight lang="objc">NSMutableArray *stack = [NSMutableArray array]; // creating
 
[stack addObject:value]; // pushing
Line 2,564 ⟶ 4,983:
[stack removeLastObject]; // popping
 
[stack count] == 0 // is empty?</langsyntaxhighlight>
 
=={{header|OCaml}}==
Implemented as a singly-linked list, wrapped in an object:
<langsyntaxhighlight lang="ocaml">exception Stack_empty
 
class ['a] stack =
Line 2,575 ⟶ 4,994:
 
method push x =
lst <- x::lst
 
method pop =
Line 2,585 ⟶ 5,004:
method is_empty =
lst = []
end</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
Stack is already defined at startup.
 
<syntaxhighlight lang="oforth">ListBuffer Class new: Stack
Stack method: push self add ;
Stack method: pop self removeLast ;
Stack method: top self last ;</syntaxhighlight>
 
Usage :
<syntaxhighlight lang="oforth">: testStack
| s |
Stack new ->s
s push(10)
s push(11)
s push(12)
s top println
s pop println
s pop println
s pop println
s isEmpty ifTrue: [ "Stack is empty" println ] ;</syntaxhighlight>
 
{{out}}
<pre>
12
12
11
10
Stack is empty
</pre>
 
=={{header|Ol}}==
Simplest stack can be implemented using 'cons' and 'uncons' primitives.
<syntaxhighlight lang="scheme">
(define stack #null)
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* pushing 1")
(define stack (cons 1 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* pushing 2")
(define stack (cons 2 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* pushing 3")
(define stack (cons 3 stack))
(print "stack is: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
 
(print "* poping")
(define-values (value stack) (uncons stack #f))
(print "value: " value)
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
</syntaxhighlight>
{{out}}
<pre>
stack is: ()
is stack empty: #true
* pushing 1
stack is: (1)
is stack empty: #false
* pushing 2
stack is: (2 1)
is stack empty: #false
* pushing 3
stack is: (3 2 1)
is stack empty: #false
* poping
value: 3
stack: (2 1)
is stack empty: #false
* poping
value: 2
stack: (1)
is stack empty: #false
* poping
value: 1
stack: ()
is stack empty: #true
* poping
value: #false
stack: ()
is stack empty: #true
</pre>
 
 
But in real programs may be useful a more complex stack implementation based on coroutines (ol is a purely functional lisp, so it does not support mutators like 'set!').
 
<syntaxhighlight lang="scheme">
(fork-server 'stack (lambda ()
(let this ((me '()))
(let*((envelope (wait-mail))
(sender msg envelope))
(case msg
(['empty]
(mail sender (null? me))
(this me))
(['push value]
(this (cons value me)))
(['pop]
(cond
((null? me)
(mail sender #false)
(this me))
(else
(mail sender (car me))
(this (cdr me))))))))))
(define (push value)
(mail 'stack ['push value]))
(define (pop)
(await (mail 'stack ['pop])))
(define (empty)
(await (mail 'stack ['empty])))
 
(for-each (lambda (n)
(print "pushing " n)
(push n))
(iota 5 1)) ; '(1 2 3 4 5)
 
(let loop ()
(print "is stack empty: " (empty))
(unless (empty)
(begin
(print "popping value, got " (pop))
(loop))))
(print "done.")
</syntaxhighlight>
 
{{out}}
<pre>
pushing 1
pushing 2
pushing 3
pushing 4
pushing 5
is stack empty: #false
popping value, got 5
is stack empty: #false
popping value, got 4
is stack empty: #false
popping value, got 3
is stack empty: #false
popping value, got 2
is stack empty: #false
popping value, got 1
is stack empty: #true
done.
</pre>
 
=={{header|ooRexx}}==
The ooRexx queue class functions as a stack as well (it is a dequeue really).
<syntaxhighlight lang="oorexx">
<lang ooRexx>
stack = .queue~of(123, 234) -- creates a stack with a couple of items
stack~push("Abc") -- pushing
Line 2,596 ⟶ 5,187:
-- the is empty test
if stack~isEmpty then say "The stack is empty"
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
The real stack is freely available!
<langsyntaxhighlight lang="oxygenbasic">
function f()
sys a=1,b=2,c=3,d=4
Line 2,621 ⟶ 5,212:
 
f
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
A thread-safe, list-based stack. Implemented as a module:
<langsyntaxhighlight lang="oz">functor
export
New
Line 2,655 ⟶ 5,246:
@Stack == nil
end
end</langsyntaxhighlight>
There is also a stack implementation in the [http://www.mozart-oz.org/home/doc/mozart-stdlib/adt/stack.html standard library].
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">push(x)=v=concat(v,[x]);;
pop()={
if(#v,
Line 2,676 ⟶ 5,267:
error("Stack underflow")
)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
This implements stacks of integers in standard Pascal (should work on all existing Pascal dialects).
<langsyntaxhighlight lang="pascal">{ tStack is the actual stack type, tStackNode a helper type }
type
pStackNode = ^tStackNode;
Line 2,734 ⟶ 5,325:
PopFromStack := node^.data;
dispose(node);
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
Perl comes prepared to treat its listsarrays as stacks, giving us the push and pop functions for free. To add empty, we basically give a new name to "not":
<langsyntaxhighlight lang="perl">sub empty{ not @_ }</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
Perl 6 still has the stack functions from Perl 5, but now they also can be accessed by object notation:
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang perl6>my @stack; # just a array
<span style="color: #000080;font-style:italic;">-- comparing a simple implementation against using the builtins:</span>
@stack.push($elem); # add $elem to the end of @stack
<span style="color: #004080;">sequence</span> <span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
$elem = @stack.pop; # get the last element back
@stack.elems == 0 # true, because the stack is empty
<span style="color: #008080;">procedure</span> <span style="color: #000000;">push_</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">)</span>
not @stack # also true because @stack is false</lang>
<span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">stack</span><span style="color: #0000FF;">,</span><span style="color: #000000;">what</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">pop_</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">what</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stack</span><span style="color: #0000FF;">[$]</span>
<span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">stack</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..$-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">what</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">empty_</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">stack</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">empty_</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<span style="color: #000000;">push_</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">empty_</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- 0</span>
<span style="color: #000000;">push_</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">pop_</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- 6</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">pop_</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- 5</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">empty_</span><span style="color: #0000FF;">()</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<span style="color: #0000FF;">?</span><span style="color: #008000;">"===builtins==="</span>
<span style="color: #7060A8;">requires</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"1.0.2"</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- (latest bugfixes, plus top renamed as peep, for p2js)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">sid</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_stack</span><span style="color: #0000FF;">()</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">stack_empty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<span style="color: #7060A8;">push</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">stack_empty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 0</span>
<span style="color: #7060A8;">push</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">--?peep(sid) -- 6 (leaving it there)</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">pop</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 6</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">pop</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 5</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">stack_empty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sid</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 1</span>
<!--</syntaxhighlight>-->
Note you get true/false rather than 1/0 under pwa/p2js (use printf(%t) for consistent results)
 
=={{header|PHP}}==
PHP arrays behave like a stack:
<langsyntaxhighlight lang="php">$stack = array();
 
empty( $stack ); // true
Line 2,760 ⟶ 5,386:
 
echo array_pop( $stack ); // outputs "2"
echo array_pop( $stack ); // outputs "1"</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
The built-in functions [http://software-lab.de/doc/refP.html#push push] and
[http://software-lab.de/doc/refP.html#pop pop] are used to maintain a stack (of any type).
<langsyntaxhighlight PicoLisplang="picolisp">(push 'Stack 3)
(push 'Stack 2)
(push 'Stack 1)</langsyntaxhighlight>
<pre>: Stack
-> (1 2 3)
Line 2,782 ⟶ 5,408:
: Stack
-> NIL</pre>
 
=={{header|Pike}}==
Pike has a built in module ''ADT'' (Abstract Data Types) which among
other things contains a stack.
 
<syntaxhighlight lang="pike">
object s = ADT.Stack();
s->push("a");
s->push("b");
write("top: %O, pop1: %O, pop2: %O\n",
s->top(), s->pop(), s->pop());
s->reset(); // Empty the stack
</syntaxhighlight>
{{Out}}
<pre>
top: "b", pop1: "b", pop2: "a"
</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* Any controlled variable may behave as a stack. */
 
declare s float controlled;
Line 2,822 ⟶ 5,465:
free s;
end;
/* The values are printed in the reverse order, of course. */</langsyntaxhighlight>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">% empty? is already defined.
/push {exch cons}.
/pop {uncons exch pop}.
Line 2,836 ⟶ 5,479:
=false
[] empty?
=true</langsyntaxhighlight>
 
=={{header|PowerShell}}==
A new stack:
<syntaxhighlight lang="powershell">
$stack = New-Object -TypeName System.Collections.Stack
# or
$stack = [System.Collections.Stack] @()
</syntaxhighlight>
Push some stuff on the stack:
<syntaxhighlight lang="powershell">
1, 2, 3, 4 | ForEach-Object {$stack.Push($_)}
</syntaxhighlight>
Show stack as a string:
<syntaxhighlight lang="powershell">
$stack -join ", "
</syntaxhighlight>
{{Out}}
<pre>
4, 3, 2, 1
</pre>
Pop the top level of the stack:
<syntaxhighlight lang="powershell">
$stack.Pop()
</syntaxhighlight>
{{Out}}
<pre>
4
</pre>
Show stack as a string:
<syntaxhighlight lang="powershell">
$stack -join ", "
</syntaxhighlight>
{{Out}}
<pre>
3, 2, 1
</pre>
Get a copy of the top level of the stack:
<syntaxhighlight lang="powershell">
$stack.Peek()
</syntaxhighlight>
{{Out}}
<pre>
3
</pre>
The stack:
<syntaxhighlight lang="powershell">
$stack
</syntaxhighlight>
{{Out}}
<pre>
3
2
1
</pre>
 
=={{header|Prolog}}==
Prolog is a particularly silly language to implement stack functions in, as the built-in lists can be treated as stacks in an ad hoc manner. Nonetheless, in the name of completeness:
<langsyntaxhighlight lang="prolog">% push( ELEMENT, STACK, NEW )
% True if NEW is [ELEMENT|STACK]
push(ELEMENT,STACK,[ELEMENT|STACK]).
Line 2,850 ⟶ 5,547:
% empty( STACK )
% True if STACK is empty
empty([]).</langsyntaxhighlight>
 
=={{header|PureBasic}}==
For LIFO function PureBasic normally uses linked lists.
Usage as described above could look like;
<langsyntaxhighlight PureBasiclang="purebasic">Global NewList MyStack()
 
Procedure Push_LIFO(n)
Line 2,892 ⟶ 5,589:
While Not Empty_LIFO()
Debug Pop_LIFO()
Wend</langsyntaxhighlight>
 
{{out}}
'''Outputs
<pre>
4
1
3
</pre>
 
=={{header|Python}}==
{{works with|Python|2.5}}
The faster and Pythonic way is using a deque (available from 2.4). A regular list is a little slower.
A regular list is a little slower.
<lang python>from collections import deque
<syntaxhighlight lang="python">from collections import deque
stack = deque()
stack.append(value) # pushing
value = stack.pop()
not stack # is empty?</langsyntaxhighlight>
If you need to expose your stack to the world, you may want to create a simpler wrapper:
<langsyntaxhighlight lang="python">from collections import deque
 
class Stack:
Line 2,918 ⟶ 5,618:
return self._items.pop()
def __nonzero__(self):
return bool(self._items)</langsyntaxhighlight>
Here is a stack implemented as linked list - with the same list interface.
<langsyntaxhighlight lang="python">class Stack:
def __init__(self):
self._first = None
Line 2,931 ⟶ 5,631:
raise IndexError, "pop from empty stack"
value, self._first = self._first
return value</langsyntaxhighlight>
Notes:
 
Using list interface - append, __nonzero__ make it easier to use, cleanup the client code, and allow changing the implementation later without affecting the client code. For example, instead of:
For example, instead of:
<lang python>while not stack.empty():</lang>
<syntaxhighlight lang="python">while not stack.empty():</syntaxhighlight>
You can write:
<syntaxhighlight lang ="python">while stack:</langsyntaxhighlight>
Quick testing show that deque is about 5 times faster then the wrapper linked list implementations. This may be important if your stack is used in tight loops.
 
=={{header|Quackery}}==
 
Quackery is a stack based language. In addition to ''the stack'' (i.e. the Quackery data stack) and the call stack, named ancillary stacks can be created with <code>[ stack ] is <name-of-stack></code>. Pushing to and popping from ancillary stacks is done with the words <code>put</code> and <code>take</code>. A word to test if an ancillary stack is empty can be defined as <code>[ size 1 = ] is isempty</code>. (The word <code>empty</code> already has a meaning in Quackery.) The word <code>share</code> returns the topmost element of an ancillary stack without changing the ancillary stack. Other ancillary stack operations are also available.
 
<syntaxhighlight lang="quackery">[ size 1 = ] is isempty ( s --> b )
 
[ stack ] is mystack ( --> s )
 
mystack isempty if [ say "mystack is empty" cr cr ]
23 mystack put
mystack share echo say " is on the top of mystack" cr cr
mystack mystack put ( you can put anything on an ancillary stack, even itself! )
mystack share echo say " is on the top of mystack" cr cr
mystack take echo say " has been removed from mystack" cr cr
mystack take echo say " has been removed from mystack" cr cr
mystack isempty if [ say "mystack is empty" cr cr ]
say "you are in a maze of twisty little passages, all alike"</syntaxhighlight>
 
{{out}}
 
<pre>mystack is empty
 
23 is on the top of mystack
 
mystack is on the top of mystack
 
mystack has been removed from mystack
 
23 has been removed from mystack
 
mystack is empty
 
you are in a maze of twisty little passages, all alike</pre>
 
=={{header|R}}==
{{libheader|proto}}
See [[FIFO]] for functional and object oriented implementations of a First-In-First-Out object, with similar code.
<langsyntaxhighlight Rlang="r">library(proto)
 
stack <- proto(expr = {
Line 2,996 ⟶ 5,733:
stack$pop()
# Error in get("pop", env = stack, inherits = TRUE)(stack, ...) :
# can't pop from an empty list</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 3,002 ⟶ 5,739:
Quick functional version:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define (stack) '())
(define (push x stack) (cons x stack))
(define (pop stack) (values (car stack) (cdr stack)))
(define (empty? stack) (null? stack))
</syntaxhighlight>
</lang>
 
And a destructive object:
 
<syntaxhighlight lang="racket">
<lang Racket>
(struct stack ([items #:auto]) #:mutable #:auto-value '())
(define (push! x stack)
Line 3,021 ⟶ 5,758:
(define (empty? stack)
(null? (stack-items stack)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Raku still has the stack functions from Perl 5, but now they also can be accessed by object notation:
<syntaxhighlight lang="raku" line>my @stack; # just a array
@stack.push($elem); # add $elem to the end of @stack
$elem = @stack.pop; # get the last element back
@stack.elems == 0 # true, because the stack is empty
not @stack # also true because @stack is false</syntaxhighlight>
 
=={{header|Raven}}==
Use built in ''stack'' type:
<langsyntaxhighlight lang="raven">new stack as s
1 s push
s pop</langsyntaxhighlight>
Word ''empty'' is also built in:
<langsyntaxhighlight lang="raven">s empty if 'stack is empty' print</langsyntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">REBOL [
Title: "Stack"
Author: oofoe
Date: 2010-10-04
URL: http://rosettacode.org/wiki/Stack
]
Line 3,067 ⟶ 5,812:
assert ['test = v/pop]
assert ['a = v/pop]
assert [not v/empty]</langsyntaxhighlight>
Sample run:
<pre>Simple integers:
Line 3,083 ⟶ 5,828:
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: stack ( n"- ) create 0 , allot ;
: push ( na- ) dup ++ dup @ + ! ;
: pop ( a-n ) dup @ over -- + @ ;
Line 3,097 ⟶ 5,842:
st top putn
st pop putn st pop putn st pop putn
st empty? putn</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">y=123 /*define a REXX variable, value is 123 */
push y /*pushes 123 onto the stack. */
pull g /*pops last value stacked & removes it. */
Line 3,107 ⟶ 5,852:
exit /*stick a fork in it, we're done. */
 
empty: return queued() /*subroutine returns # of stacked items.*/</langsyntaxhighlight>
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* supports push, pull, and peek
* 11.08.2013 Walter Pachl
Line 3,151 ⟶ 5,896:
 
empty: Procedure Expose stk.
Return stk.0=0</langsyntaxhighlight>
{{out}}
Output:
<pre>
0
Line 3,163 ⟶ 5,908:
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Stack
 
load "stdlib.ring"
ostack = new stack
for n = 5 to 7
see "Push: " + n + nl
ostack.push(n)
next
see "Pop:" + ostack.pop() + nl
see "Push: " + "8" + nl
ostack.push(8)
while len(ostack) > 0
see "Pop:" + ostack.pop() + nl
end
if len(ostack) = 0
see "Pop: stack is empty" + nl
ok
</syntaxhighlight>
Output:
<pre>
Push: 5
Push: 6
Push: 7
Pop:7
Push: 8
Pop:8
Pop:6
Pop:5
Pop: stack is empty
</pre>
 
=={{header|RPL}}==
The RPL interpreter is based on a stack, with which the user interacts.
*the push operation is performed by the <code>DUP</code> instruction
*the pop operation by <code>DROP</code>
*<code>DEPTH</code> provides the stack size. To test the emptiness of the stack, the following program can be created as an user-defined instruction:
≪ DEPTH NOT ≫ 'EMPTY?' STO
=={{header|Ruby}}==
Using an Array, there are already methods Array#push, Array#pop and Array#empty?.
<langsyntaxhighlight lang="ruby">stack = []
stack.push(value) # pushing
value = stack.pop # popping
stack.empty? # is empty?</langsyntaxhighlight>
If you need to expose your stack to the world, you may want to create a simpler wrapper. Here is a wrapper class ''Stack'' that wraps ''Array'' but only exposes stack methods.
<langsyntaxhighlight lang="ruby">require 'forwardable'
 
# A stack contains elements in last-in, first-out order.
Line 3,177 ⟶ 5,961:
class Stack
extend Forwardable
 
# Creates a Stack containing _objects_.
def self.[](*objects)
new.push(*objects)
end
 
# Creates an empty Stack.
def initialize
@ary = []
end
 
# Duplicates a Stack.
def initialize_copy(obj)
Line 3,193 ⟶ 5,977:
@ary = @ary.dup
end
 
# Adds each object to the top of this Stack. Returns self.
def push(*objects)
Line 3,200 ⟶ 5,984:
end
alias << push
 
##
# :method: pop
Line 3,213 ⟶ 5,997:
# an Array of them. If this Stack contains fewer than _n_ elements,
# returns them all. If this Stack is empty, returns an empty Array.
def_delegator :@ary, :pop
nil
 
##
if ([].pop(0) rescue false)
# Ruby >=:method: 1.8.7top
# :call-seq:
def_delegator :@ary, :pop
# top -> obj or nil
else
# # Rubytop(n) <-> 1.8.7ary
# Returns the topmost element without modifying the stack.
def pop(*args) # :nodoc:
def_delegator :@ary, :last, :top
case len = args.length
when 0
@ary.pop
when 1
n = [@ary.length, args.first].min
@ary.slice!(-n, n)
else
raise ArgumentError, "wrong number of arguments (#{len} for 0..1)"
end
end
end
 
##
# :method: empty?
# Returns true if this Stack contains no elements.
def_delegator :@ary, :empty?
 
##
# :method: size
Line 3,243 ⟶ 6,017:
def_delegator :@ary, :size
alias length size
 
# Converts this Stack to a String.
def to_s
Line 3,249 ⟶ 6,023:
end
alias inspect to_s
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby">p s = Stack.new # => Stack[]
p s.empty? # => true
p s.pop size # => nil0
p s.pop(1) top # => []nil
p s.push(1) pop # => Stack[1]nil
p s.pushpop(2, 31) # => Stack[1, 2, 3]
p s.pop push(1) # => 3Stack[1]
p s.poppush(12, 3) # => Stack[1, 2, 3]
p s.empty? top # => false3
p s.top(2) # => [2, 3]
p s # => Stack[1, 2, 3]
p s.size # => 3
p s.pop # => 3
p s.pop(1) # => [2]
p s.empty? # => false
 
p s = Stack[:a, :b, :c] # => Stack[:a, :b, :c]
p s.pop << :d # => Stack[:a, :b, :c</lang>, :d]
p s.pop # => :d</syntaxhighlight>
 
Just meeting the requirements of a push, pop and empty method:
<syntaxhighlight lang="ruby">require 'forwardable'
 
class Stack
extend Forwardable
 
def initialize
@stack = []
end
 
def_delegators :@stack, :push, :pop, :empty?
end
</syntaxhighlight>
(push takes multiple arguments; pop takes an optional argument which specifies how many to pop)
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">dim stack$(10) ' stack of ten
global stack$
global stackEnd
Line 3,305 ⟶ 6,101:
FUNCTION mt$()
stackEnd = 0
END FUNCTION</langsyntaxhighlight>
{{out}}
Output:
<pre>Pushed A stack has 1
Pushed B stack has 2
Line 3,315 ⟶ 6,111:
Pop Value:D stack has 3
Empty stack. stack has 0</pre>
 
=={{header|Rust}}==
===Using the standard library===
 
One could just use a vector (<code>Vec<T></code>) which is part of the standard library
 
<syntaxhighlight lang="rust">fn main() {
let mut stack = Vec::new();
stack.push("Element1");
stack.push("Element2");
stack.push("Element3");
 
assert_eq!(Some(&"Element3"), stack.last());
assert_eq!(Some("Element3"), stack.pop());
assert_eq!(Some("Element2"), stack.pop());
assert_eq!(Some("Element1"), stack.pop());
assert_eq!(None, stack.pop());
}</syntaxhighlight>
 
===Simple implementation===
Simply uses a singly-linked list.
<syntaxhighlight lang="rust">type Link<T> = Option<Box<Frame<T>>>;
 
pub struct Stack<T> {
head: Link<T>,
}
struct Frame<T> {
elem: T,
next: Link<T>,
}
 
/// Iterate by value (consumes list)
pub struct IntoIter<T>(Stack<T>);
impl<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.0.pop()
}
}
 
/// Iterate by immutable reference
pub struct Iter<'a, T: 'a> {
next: Option<&'a Frame<T>>,
}
impl<'a, T> Iterator for Iter<'a, T> { // Iterate by immutable reference
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|frame| {
self.next = frame.next.as_ref().map(|frame| &**frame);
&frame.elem
})
}
}
 
/// Iterate by mutable reference
pub struct IterMut<'a, T: 'a> {
next: Option<&'a mut Frame<T>>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.next.take().map(|frame| {
self.next = frame.next.as_mut().map(|frame| &mut **frame);
&mut frame.elem
})
}
}
 
 
impl<T> Stack<T> {
/// Return new, empty stack
pub fn new() -> Self {
Stack { head: None }
}
 
/// Add element to top of the stack
pub fn push(&mut self, elem: T) {
let new_frame = Box::new(Frame {
elem: elem,
next: self.head.take(),
});
self.head = Some(new_frame);
}
 
/// Remove element from top of stack, returning the value
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|frame| {
let frame = *frame;
self.head = frame.next;
frame.elem
})
}
 
/// Get immutable reference to top element of the stack
pub fn peek(&self) -> Option<&T> {
self.head.as_ref().map(|frame| &frame.elem)
}
 
/// Get mutable reference to top element on the stack
pub fn peek_mut(&mut self) -> Option<&mut T> {
self.head.as_mut().map(|frame| &mut frame.elem)
}
 
/// Iterate over stack elements by value
pub fn into_iter(self) -> IntoIter<T> {
IntoIter(self)
}
 
/// Iterate over stack elements by immutable reference
pub fn iter<'a>(&'a self) -> Iter<'a,T> {
Iter { next: self.head.as_ref().map(|frame| &**frame) }
}
 
/// Iterate over stack elements by mutable reference
pub fn iter_mut(&mut self) -> IterMut<T> {
IterMut { next: self.head.as_mut().map(|frame| &mut **frame) }
}
}
 
// The Drop trait tells the compiler how to free an object after it goes out of scope.
// By default, the compiler would do this recursively which *could* blow the stack for
// extraordinarily long lists. This simply tells it to do it iteratively.
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
let mut cur_link = self.head.take();
while let Some(mut boxed_frame) = cur_link {
cur_link = boxed_frame.next.take();
}
}
}</syntaxhighlight>
 
=={{header|Sather}}==
This one uses a builtin linked list to keep the values pushed onto the stack.
<langsyntaxhighlight lang="sather">class STACK{T} is
private attr stack :LLIST{T};
 
Line 3,350 ⟶ 6,276:
return stack.is_empty;
end;
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
s ::= #STACK{INT};
Line 3,365 ⟶ 6,291:
until!(s.is_empty); end;
end;
end;</langsyntaxhighlight>
Sather library has the abstract class <code>$STACK{T}</code>, but using this forces us to implement other methods too.
 
=={{header|Scala}}==
The Do it yourself approach:
[[Category:Scala Implementations]]
The<syntaxhighlight Do it yourself approach.<lang Scala="scala">class Stack[T] {
private var items = List[T]()
 
Line 3,386 ⟶ 6,312:
 
def push(value: T) = items = value +: items
}</langsyntaxhighlight>
Or use the standard Scala library. Slightly modified to meet to requirements of this task.<lang scala>import collection.mutable.{ Stack => Stak }
Slightly modified to meet to requirements of this task.
<syntaxhighlight lang="scala">import collection.mutable.{ Stack => Stak }
 
class Stack[T] extends Stak[T] {
Line 3,395 ⟶ 6,323:
}
def peek: T = this.head
}</langsyntaxhighlight>A test could be:<syntaxhighlight lang Scala="scala">object StackTest extends App {
 
val stack = new Stack[String]
Line 3,407 ⟶ 6,335:
assert(stack.pop() == "Peter Pan")
println("Completed without errors")
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
This version uses primitive message passing.
<langsyntaxhighlight lang="scheme">(define (make-stack)
(let ((st '()))
(lambda (message . args)
Line 3,425 ⟶ 6,353:
(set! st (cdr st))
result)))
(else 'badmsg)))))</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func type: stack (in type: baseType) is func
Line 3,468 ⟶ 6,396:
writeln(pop(s) = 10);
writeln(empty(s));
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">put () into stack
repeat with each item of 1 .. 10
push it into stack
end repeat
 
repeat while stack is not empty
pop stack
put it
end repeat</syntaxhighlight>
 
=={{header|Sidef}}==
Using a built-in array:
<syntaxhighlight lang="ruby">var stack = [];
stack.push(42); # pushing
say stack.pop; # popping
say stack.is_empty; # is_emtpy?</syntaxhighlight>
 
Creating a Stack class:
<syntaxhighlight lang="ruby">class Stack(stack=[]) {
method pop { stack.pop };
method push(item) { stack.push(item) };
method empty { stack.is_empty };
}
 
var stack = Stack();
stack.push(42);
say stack.pop; # => 42
say stack.empty; # => true</syntaxhighlight>
 
=={{header|Slate}}==
From Slate's standard library:
<langsyntaxhighlight lang="slate">collections define: #Stack &parents: {ExtensibleArray}.
"An abstraction over ExtensibleArray implementations to follow the stack
protocol. The convention is that the Sequence indices run least-to-greatest
Line 3,493 ⟶ 6,451:
 
s@(Stack traits) bottom
[s first].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Smalltalk has a built-in Stack class, instances of which you can send messages:
<syntaxhighlight lang="smalltalk">
s := Stack new.
s push: 1.
s push: 2.
s push: 3.
s pop.
s top. "2"
</syntaxhighlight>
 
=={{header|Standard ML}}==
 
The signature for a module supplying a stack interface, with a couple added functions.
 
<syntaxhighlight lang="sml">signature STACK =
sig
type 'a stack
exception EmptyStack
 
val empty : 'a stack
val isEmpty : 'a stack -> bool
 
val push : ('a * 'a stack) -> 'a stack
val pop : 'a stack -> 'a stack
val top : 'a stack -> 'a
val popTop : 'a stack -> 'a stack * 'a
 
val map : ('a -> 'b) -> 'a stack -> 'b stack
val app : ('a -> unit) -> 'a stack -> unit
end</syntaxhighlight>
 
An implementation of the <code>STACK</code> signature, using immutable lists.
 
<syntaxhighlight lang="sml">structure Stack :> STACK =
struct
type 'a stack = 'a list
exception EmptyStack
 
val empty = []
 
fun isEmpty st = null st
 
fun push (x, st) = x::st
 
fun pop [] = raise EmptyStack
| pop (x::st) = st
 
fun top [] = raise EmptyStack
| top (x::st) = x
 
fun popTop st = (pop st, top st)
 
fun map f st = List.map f st
fun app f st = List.app f st
end</syntaxhighlight>
 
=={{header|Stata}}==
See [[Singly-linked list/Element definition#Stata]].
 
=={{header|Swift}}==
Generic stack.
<syntaxhighlight lang="swift">struct Stack<T> {
var items = [T]()
var empty:Bool {
return items.count == 0
}
func peek() -> T {
return items[items.count - 1]
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func push(obj:T) {
items.append(obj)
}
}
 
var stack = Stack<Int>()
stack.push(1)
stack.push(2)
println(stack.pop())
println(stack.peek())
stack.pop()
println(stack.empty)</syntaxhighlight>
{{out}}
<pre>
2
1
true
</pre>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
processor Stack
@: $;
 
sink push
..|@Stack: $;
end push
 
source peek
$@Stack(last) !
end peek
 
source pop
^@Stack(last) !
end pop
 
source empty
$@Stack::length -> #
<=0> 1 !
<> 0 !
end empty
end Stack
 
def myStack: [1] -> Stack;
 
2 -> !myStack::push
 
'$myStack::empty; $myStack::pop;
' -> !OUT::write
'$myStack::empty; $myStack::pop;
' -> !OUT::write
'$myStack::empty;
' -> !OUT::write
 
3 -> !myStack::push
'$myStack::empty; $myStack::peek;
' -> !OUT::write
'$myStack::empty; $myStack::pop;
' -> !OUT::write
'$myStack::empty;' -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>
0 2
0 1
1
0 3
0 3
1
</pre>
 
=={{header|Tcl}}==
Here's a simple implementation using a list:
<langsyntaxhighlight lang="tcl">proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
Line 3,527 ⟶ 6,632:
peek S ;# ==> bar
pop S ;# ==> bar
peek S ;# ==> foo</langsyntaxhighlight>
{{tcllib|struct::stack}}
<langsyntaxhighlight lang="tcl">package require struct::stack
struct::stack S
S size ;# ==> 0
Line 3,538 ⟶ 6,643:
S peek ;# ==> d
S pop 4 ;# ==> d c b a
S size ;# ==> 0</langsyntaxhighlight>
 
=={{header|Uiua}}==
 
<syntaxhighlight lang="Uiua">
[3] # Since UIUA is a stack language, everything is pushed on the stack
x ← # stores the top of the stack into the variable x
? # ? checks the stack, it is now empty
 
</syntaxhighlight>
 
 
 
=={{header|UnixPipes}}==
<langsyntaxhighlight lang="bash">init() { if [ -e stack ]; then rm stack; fi } # force pop to blow up if empty
push() { echo $1 >> stack; }
pop() {
Line 3,551 ⟶ 6,667:
}
empty() { head -n -1 stack |wc -l; }
stack_top() { tail -1 stack; }</langsyntaxhighlight>
test it:
<langsyntaxhighlight lang="bash">% push me; push you; push us; push them
% pop;pop;pop;pop
them
us
you
me</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Zsh}}
{{works with|Korn Shell}}
 
Here's a simple single-stack solution:
<syntaxhighlight lang="sh">init() {
if [[ -n $KSH_VERSION ]]; then
set -A stack
else
stack=(); # this sets stack to '()' in ksh
fi
}
 
push() {
stack=("$1" "${stack[@]}")
}
 
stack_top() {
# this approach sidesteps zsh indexing difference
set -- "${stack[@]}"
printf '%s\n' "$1"
}
 
pop() {
stack_top
stack=("${stack[@]:1}")
}
 
empty() {
(( ${#stack[@]} == 0 ))
}
 
# Demo
push fred; push wilma; push betty; push barney
printf 'peek(stack)==%s\n' "$(stack_top)"
while ! empty; do
pop
done</syntaxhighlight>
 
{{Out}}
<pre>peek(stack)==barney
barney
betty
wilma
fred</pre>
 
You can generalize it to multiple stacks with some judicious use of the twin evils of pass-by-name and <tt>eval</tt>:
 
<syntaxhighlight lang="sh">init_stack() {
if [[ -n $KSH_VERSION ]]; then
eval 'set -A '"$1"
else
eval "$1=()"
fi
}
 
push() {
eval "$1"'=("$2" "${'"$1"'[@]}")'
}
 
stack_top() {
eval 'set -- "${'"$1"'[@]}"';
printf '%s\n' "$1"
}
 
pop() {
stack_top "$1";
eval "$1"'=("${'"$1"'[@]:1}")'
}
 
empty() {
eval '(( ${#'"$1"'[@]} == 0 ))'
}
 
init_stack mystack
push mystack fred; push mystack wilma; push mystack betty; push mystack barney
printf 'peek(mystack)==%s\n' "$(stack_top mystack)"
while ! empty mystack; do
pop mystack
done</syntaxhighlight>
 
{{Out}}
<pre>peek(mystack)==barney
barney
betty
wilma
fred</pre>
 
=={{header|VBA}}==
Define a class Stack in a class module with that name.
<langsyntaxhighlight lang="vb">'Simple Stack class
 
'uses a dynamic array of Variants to stack the values
Line 3,598 ⟶ 6,803:
Property Get Size() As Integer
Size = myStackHeight
End Property</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="vb">'stack test
Public Sub stacktest()
Dim aStack As New Stack
Line 3,620 ⟶ 6,825:
.Pop
End With
End Sub</langsyntaxhighlight>
{{out}}
Output:
<pre>
stacktest
Line 3,633 ⟶ 6,838:
 
=={{header|VBScript}}==
===Stack class===
<langsyntaxhighlight lang="vb">class stack
dim tos
dim stack()
Line 3,689 ⟶ 6,894:
wscript.echo s.pop
if s.stackempty then exit for
next</langsyntaxhighlight>
Output{{out}} (changes every time)
<pre>-1
9
Line 3,712 ⟶ 6,917:
0.533424
0.7055475</pre>
===Using an ArrayList.===
<syntaxhighlight lang="vb">' Stack Definition - VBScript
Option Explicit
 
Dim stack, i, x
Set stack = CreateObject("System.Collections.ArrayList")
If Not empty_(stack) Then Wscript.Echo stack.Count
push stack, "Banana"
push stack, "Apple"
push stack, "Pear"
push stack, "Strawberry"
Wscript.Echo "Count=" & stack.Count ' --> Count=4
Wscript.Echo pop(stack) & " - Count=" & stack.Count ' --> Strawberry - Count=3
Wscript.Echo "Tail=" & stack.Item(0) ' --> Tail=Banana
Wscript.Echo "Head=" & stack.Item(stack.Count-1) ' --> Head=Pear
Wscript.Echo stack.IndexOf("Apple", 0) ' --> 1
For i=1 To stack.Count
Wscript.Echo join(stack.ToArray(), ", ")
x = pop(stack)
Next 'i
 
Sub push(s, what)
s.Add what
End Sub 'push
Function pop(s)
Dim what
If s.Count > 0 Then
what = s(s.Count-1)
s.RemoveAt s.Count-1
Else
what = ""
End If
pop = what
End Function 'pop
Function empty_(s)
empty_ = s.Count = 0
End Function 'empty_ </syntaxhighlight>
{{out}}
<pre>
Count=4
Strawberry - Count=3
Tail=Banana
Head=Pear
1
Banana, Apple, Pear
Banana, Apple
Banana
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="go">const (
max_depth = 256
)
 
struct Stack {
mut:
data []f32 = []f32{len: max_depth}
depth int
}
 
fn (mut s Stack) push(v f32) {
if s.depth >= max_depth {
return
}
println('Push: ${v:3.2f}')
s.data[s.depth] = v
s.depth++
}
 
fn (mut s Stack) pop() ?f32 {
if s.depth > 0 {
s.depth--
result := s.data[s.depth]
println('Pop: top of stack was ${result:3.2f}')
return result
}
return error('Stack Underflow!!')
}
 
fn (s Stack) peek() ?f32 {
if s.depth > 0 {
result := s.data[s.depth - 1]
println('Peek: top of stack is ${result:3.2f}')
return result
}
return error('Out of Bounds...')
}
 
fn (s Stack) empty() bool {
return s.depth == 0
}
 
fn main() {
mut stack := Stack{}
println('Stack is empty? ' + if stack.empty() { 'Yes' } else { 'No' })
stack.push(5.0)
stack.push(4.2)
println('Stack is empty? ' + if stack.empty() { 'Yes' } else { 'No' })
stack.peek() or { return }
stack.pop() or { return }
stack.pop() or { return }
}
</syntaxhighlight>
{{out}}
<pre>Stack is empty? Yes
Push: 5.00
Push: 4.20
Stack is empty? No
Peek: top of stack is 4.20
Pop: top of stack was 4.20
Pop: top of stack was 5.00
</pre>
 
=={{header|Wart}}==
Line 3,717 ⟶ 7,037:
Stacks as user-defined objects backed by a list.
 
<langsyntaxhighlight lang="wart">def (stack)
(tag 'stack nil)
 
Line 3,727 ⟶ 7,047:
 
def (empty? s) :case (isa stack s)
(empty? rep.s)</langsyntaxhighlight>
 
Example usage:
Line 3,749 ⟶ 7,069:
(empty? s)
=> 1 # true</pre>
 
=={{header|Wren}}==
{{libheader|Wren-seq}}
This uses the Stack class in the above module.
<syntaxhighlight lang="wren">import "./seq" for Stack
 
var s = Stack.new()
s.push(1)
s.push(2)
System.print("Stack contains %(s.toList)")
System.print("Number of elements in stack = %(s.count)")
var item = s.pop()
System.print("'%(item)' popped from the stack")
System.print("Last element is now %(s.peek())")
s.clear()
System.print("Stack cleared")
System.print("Is stack now empty? %((s.isEmpty) ? "yes" : "no")")</syntaxhighlight>
 
{{out}}
<pre>
Stack contains [1, 2]
Number of elements in stack = 2
'2' popped from the stack
Last element is now 1
Stack cleared
Is stack now empty? yes
</pre>
 
=={{header|X86 Assembly}}==
<syntaxhighlight lang="x86asm">
; x86_64 linux nasm
 
struc Stack
maxSize: resb 8
currentSize: resb 8
contents:
endStruc
 
section .data
 
soError: db "Stack Overflow Exception", 10
seError: db "Stack Empty Error", 10
 
 
section .text
 
createStack:
; IN: max number of elements (rdi)
; OUT: pointer to new stack (rax)
push rdi
xor rdx, rdx
mov rbx, 8
mul rbx
mov rcx, rax
mov rax, 12
mov rdi, 0
syscall
push rax
mov rdi, rax
add rdi, rcx
mov rax, 12
syscall
pop rax
pop rbx
mov qword [rax + maxSize], rbx
mov qword [rax + currentSize], 0
ret
 
 
push:
; IN: stack to operate on (stack argument), element to push (rdi)
; OUT: void
mov rax, qword [rsp + 8]
mov rbx, qword [rax + currentSize]
cmp rbx, qword [rax + maxSize]
je stackOverflow
lea rsi, [rax + contents + 8*rbx]
mov qword [rsi], rdi
add qword [rax + currentSize], 1
ret
 
 
pop:
; pop
; IN: stack to operate on (stack argument)
; OUT: element from stack top
mov rax, qword [rsp + 8]
mov rbx, qword [rax + currentSize]
cmp rbx, 0
je stackEmpty
sub rbx, 1
lea rsi, [rax + contents + 8*rbx]
mov qword [rax + currentSize], rbx
mov rax, qword [rsi]
ret
 
 
; stack operation exceptions
stackOverflow:
mov rsi, soError
mov rdx, 25
jmp errExit
stackEmpty:
mov rsi, seError
mov rdx, 18
errExit:
mov rax, 1
mov rdi, 1
syscall
mov rax, 60
mov rdi, 1
syscall
</syntaxhighlight>
 
=={{header|XLISP}}==
This is a fairly straightforward implementation, representing a stack as a linked list inside an object.
<syntaxhighlight lang="lisp">(define-class stack
(instance-variables vals))
 
(define-method (stack 'initialize)
(setq vals '())
self)
 
(define-method (stack 'push x)
(setq vals (cons x vals)))
 
(define-method (stack 'pop)
(define tos (car vals))
(setq vals (cdr vals))
tos)
 
(define-method (stack 'emptyp)
(null vals))</syntaxhighlight>
A sample REPL session:
<syntaxhighlight lang="lisp">; Loading 'stack.lsp'
[1] (define st (stack 'new))
 
ST
[2] (st 'push 1)
 
(1)
[3] (st 'push 2)
 
(2 1)
[4] (st 'emptyp)
 
()
[5] (st 'pop)
 
2
[6] (st 'pop)
 
1
[7] (st 'emptyp)
 
#T
[8] </syntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int Stack(100), SP;
 
Line 3,779 ⟶ 7,256:
while not Empty do [IntOut(0, Pop); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Output:
<pre>
100
100 81 64 49 36 25 16 9 4 1 0
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">limit = 1000
dim stack(limit)
 
top = 0
 
sub push(n)
if top < limit then
top = top + 1 : stack(top) = n
else
print "stack full - ";
end if
end sub
 
sub pop()
if top then
top = top - 1 : return stack(top + 1)
else
print "stack empty - ";
end if
end sub
 
sub empty()
return not top
end sub
 
// ======== test ========
 
for n = 3 to 5
print "Push ", n : push(n)
next
 
print "Pop ", pop()
 
print "Push ", 6 : push(6)
 
while(not empty())
print "Pop ", pop()
wend
 
print "Pop ", pop()
</syntaxhighlight>
=={{header|Z80 Assembly}}==
 
The stack can be initialized by loading it directly with an immediate value. Z80-based home computers such as the Amstrad CPC and ZX Spectrum do this for you. Messing with the stack on those systems is a bad idea, since an assembly program stored on a floppy disk or cassette tape begins with the return address of BASIC on top of the stack. However, on embedded systems like the Game Boy or the Sega Master System, this step is a must, as the CPU does ''not'' have an initial stack pointer value in its vector table and thus does not guarantee the value of SP upon startup. Unlike the 6502, the Z80's stack does not have a fixed size or memory location, and is only limited by the address space of the CPU. From a practical standpoint, however, it's very unlikely you'll need more than 256 bytes.
 
<syntaxhighlight lang="z80">LD SP,&FFFF</syntaxhighlight>
 
 
Registers must be pushed in pairs. If you push/pop the accumulator, the processor flags go with it. This can make certain functions difficult to write without using a temporary variable to hold the accumulator, which doesn't allow for recursion or arbitrary nesting.
<syntaxhighlight lang="z80">push af
push bc
push de
push hl</syntaxhighlight>
 
Popping is very similar. To properly pop values, they must be popped in the reverse order they were pushed.
<syntaxhighlight lang="z80">pop hl
pop de
pop bc
pop af</syntaxhighlight>
 
The stack is empty if its value equals the original starting value of the stack pointer. This is a little difficult, since the stack doesn't necessarily start in a fixed location like it does on the 6502. There are two ways to do this:
 
<syntaxhighlight lang="z80">ld (&nnnn),SP ;&nnnn represents a memory location that the programmer will later read from to use as a
;comparison for the current stack pointer</syntaxhighlight>
 
<syntaxhighlight lang="z80">ld hl,0
add hl,sp ;the z80 doesn't allow you to load SP directly into HL, so this is the quickest way</syntaxhighlight>
 
From there it's a matter of comparing this value to the current stack pointer, which in itself is tricky since the built-in compare instruction forces you to use the accumulator as one of the operands, and works natively in terms of 8-bit values.
 
Peek can be achieved with the <code>EX (SP),HL</code> command which exchanges HL with the top item of the stack.
 
On the Game Boy, the stack can also be manually adjusted by a signed 8-bit constant. A Zilog Z80 cannot do this in a single command. The code below only works on a Game Boy or any other hardware running on a Sharp LR35902 CPU:
<syntaxhighlight lang="z80"> ADD SP,&FE ;subtract two from the stack pointer. Remember that the stack grows "down" in memory.</syntaxhighlight>
 
It should be noted that although the "heap" and the "stack" are considered separate areas of memory by the programmer, in the eyes of the CPU there is no boundary between them. The CPU doesn't care if you push enough words onto the stack so that the stack pointer is now pointing to the heap, or even ROM space. Most of the time this isn't an issue, as long as your push/pop operations are properly balanced. It's just something to look out for.
 
=={{header|zkl}}==
Lists have stack methods so this class is somewhat reduntant
<langsyntaxhighlight lang="zkl">class Stack{
var [const] stack=L();
fcn push(x){stack.append(x); self}
Line 3,795 ⟶ 7,350:
fcn empty {(not stack.len())}
var [proxy] isEmpty = empty;
}</langsyntaxhighlight>
{{out}}
<pre>
1

edit