Stack: Difference between revisions

25,136 bytes added ,  1 month ago
m
m (Only language name goes in header)
 
(25 intermediate revisions by 17 users not shown)
Line 44:
{{trans|Crystal}}
 
<langsyntaxhighlight lang="11l">[Int] stack
 
L(i) 1..10
Line 50:
 
L 10
print(stack.pop())</langsyntaxhighlight>
 
{{out}}
Line 69:
 
Push:
<syntaxhighlight lang ="6502asm">PHA</langsyntaxhighlight>
Pop:
<syntaxhighlight lang ="6502asm">PLA</langsyntaxhighlight>
Empty:
<langsyntaxhighlight lang="6502asm">TSX
CPX $FF
BEQ stackEmpty</langsyntaxhighlight>
Peek:
<langsyntaxhighlight lang="6502asm">TSX
LDA $0101,x</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
Line 85:
===Push===
You can push the contents of one or more variables.
<langsyntaxhighlight 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</langsyntaxhighlight>
 
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.
Line 92:
===Pop===
The pop is just a reverse push.
<langsyntaxhighlight lang="68000devpac">MOVEM.L (A0)+,D0-D3 ;returns the four longs stored in the stack back to where they came from.</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight lang="68000devpac">CMPA.L #userStack,A0
BEQ StackIsEmpty</langsyntaxhighlight>
 
===Manually adjusting the stack===
You can offset the user stack (and the real stack) as follows:
<langsyntaxhighlight lang="68000devpac">LEA (4,SP),SP ;does the same thing to the stack as popping 4 bytes, except those bytes are not retrieved.</langsyntaxhighlight>
 
===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.
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="asm">push ax ;push ax onto the stack
pop ax ; pop the top two bytes of the stack into ax</langsyntaxhighlight>
 
The "high" byte is pushed first, then the low byte. Popping does the opposite.
Line 122:
 
The easiest way to "peek" is to pop then push that same register again.
<langsyntaxhighlight lang="asm">;get the top item of the stack
pop ax
push ax</langsyntaxhighlight>
 
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.
Line 133:
This works for ABAP Version 7.40 and above
 
<syntaxhighlight lang="abap">
<lang ABAP>
report z_stack.
 
Line 339:
stack3->pop( ).
write: |pop -> Stack3 = { stack3->stringify( ) }|, /, /.
</syntaxhighlight>
</lang>
 
{{out}}
Line 364:
=={{header|Action!}}==
===Static memory===
<langsyntaxhighlight Actionlang="action!">DEFINE MAXSIZE="200"
BYTE ARRAY stack(MAXSIZE)
BYTE stacksize=[0]
Line 423:
TestPop()
TestPop()
RETURN</langsyntaxhighlight>
 
===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}}
<langsyntaxhighlight Actionlang="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!
Line 505:
TestPop()
TestPop()
RETURN</langsyntaxhighlight>
{{out}}
Error at the end of program is intentional.
Line 528:
=={{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 551:
Next : Stack := null;
end record;
end Generic_Stack;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">with Ada.Unchecked_Deallocation;
 
package body Generic_Stack is
Line 593:
end Pop;
 
end Generic_Stack;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 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 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 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 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 705:
# OR example stack ISNT obj stack empty #
printf((diet item fmt, obj stack pop(example stack), $l$))
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 719:
===ALGOL 68: Using FLEX array===
An alternative to using a linked list is to use a FLEX array.
<langsyntaxhighlight lang="algol68">
MODE DIETITEM = STRUCT (
STRING food, annual quantity, units, REAL cost
Line 765:
printf((diet item fmt, POP example stack, $l$))
OD
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 778:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% define a Stack type that will hold StringStackElements %
% and the StringStackElement type %
Line 825:
)
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 835:
 
=={{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 874:
730 LET EMPTY = SP = 0
740 RETURN
</syntaxhighlight>
</lang>
 
{{out}}
Line 890:
 
Pushing and popping multiple values is very similar to [[68000 Assembly]].
<langsyntaxhighlight ARMlang="arm Assemblyassembly">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.)</langsyntaxhighlight>
 
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.
Line 898:
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:
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly">LDR r0,[sp] ;load the top of the stack into r0</langsyntaxhighlight>
 
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.
Line 904:
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.
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly">;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"
 
Line 912:
;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</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="rebol">Stack: $[]-> []
 
pushTo: function [st val]-> 'st ++ val
Line 939:
 
emptyStack st
print ["finally:" st]</langsyntaxhighlight>
 
{{out}}
Line 947:
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 987 ⟶ 1,195:
return 0
}
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function deque(arr) {
arr["start"] = 0
arr["end"] = 0
Line 1,051 ⟶ 1,259:
}
printdeque(q)
}</langsyntaxhighlight>
 
=={{header|Axe}}==
 
<langsyntaxhighlight lang="axe">0→S
Lbl PUSH
r₁→{L₁+S}ʳ
Line 1,068 ⟶ 1,276:
Lbl EMPTY
S≤≤0
Return</langsyntaxhighlight>
 
=={{header|Babel}}==
<langsyntaxhighlight lang="babel">main :
{ (1 2 3) foo set -- foo = (1 2 3)
4 foo push -- foo = (1 2 3 4)
Line 1,088 ⟶ 1,296:
"empty" .
cr << }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,096 ⟶ 1,304:
=={{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 1,164 ⟶ 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 1,198 ⟶ 1,407:
= (sptr% = 0)
ENDCASE
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 1,257 ⟶ 1,466:
Representing the stack as an array, pushing is appending, popping is removing the last element, and checking emptiness is checking the length.
 
<langsyntaxhighlight lang="bqn"> Push ← ∾
Pop ← ¯1⊸↓
Line 1,270 ⟶ 1,479:
0
Empty ⟨⟩
1</langsyntaxhighlight>
 
=={{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 1,305 ⟶ 1,514:
)
&
);</langsyntaxhighlight>
{{out}}
<pre>not to be
Line 1,320 ⟶ 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}}
Line 1,334 ⟶ 1,543:
=={{header|C}}==
Macro expanding to type flexible stack routines.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,395 ⟶ 1,604:
stk_int_delete(stk);
return 0;
}</langsyntaxhighlight>
===Or===
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
Line 1,467 ⟶ 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 1,482 ⟶ 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 1,545 ⟶ 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 1,568 ⟶ 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 1,585 ⟶ 1,794:
(empty-stack? [] (= () (deref elements))))
 
(def stack (Stack (ref ())))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Stack
stack = cluster [T: type] is new, push, pop, peek, empty
rep = array[T]
Line 1,642 ⟶ 1,851:
stream$putl(po, "The stack is empty.")
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>10
Line 1,665 ⟶ 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,935 ⟶ 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,975 ⟶ 2,184:
 
COPY stack-utilities.
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,005 ⟶ 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 2,029 ⟶ 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 2,144 ⟶ 2,353:
END Stacks.
</syntaxhighlight>
</lang>
 
Execute: ^Q Stacks.TestStack<br/>
Line 2,155 ⟶ 2,364:
=={{header|Crystal}}==
 
<langsyntaxhighlight lang="ruby">stack = [] of Int32
(1..10).each do |x|
stack.push x
Line 2,162 ⟶ 2,371:
10.times do
puts stack.pop
end</langsyntaxhighlight>
 
'''Output:'''
Line 2,181 ⟶ 2,390:
=={{header|D}}==
Generic stack class implemented with a dynamic array.
<langsyntaxhighlight lang="d">import std.array;
 
class Stack(T) {
Line 2,206 ⟶ 2,415:
assert(s.pop() == 10);
assert(s.empty());
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program Stack;
 
{$APPTYPE CONSOLE}
Line 2,232 ⟶ 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">
<lang Delphi>
var stack: array of Integer;
 
Line 2,248 ⟶ 2,457:
 
Assert(stack.Length = 0); // assert empty
</syntaxhighlight>
</lang>
 
=={{header|Dyalect}}==
Line 2,254 ⟶ 2,463:
{{trans|Swift}}
 
<syntaxhighlight lang ="dyalect">type Stack =() {
var arrxs = []
}
static func Stack.StackIsEmpty() => this!xs.ini.arrLength() == []0
func Stack.isEmptyPeek() => this!xs[this!xs.ini.arr.lenLength() ==- 01]
func Stack.peekPop() => this.ini.arr[this.ini.arr.len() - 1]{
var e = this!xs[this!xs.Length() - 1]
this!xs.RemoveAt(this!xs.Length() - 1)
func Stack.pop() {
var e = this.ini.arr[this.ini.arr.len() - 1]
this.ini.arr.removeAt(this.ini.arr.len() - 1)
return e
}
func Stack.pushPush(item) {=> this!xs.Add(item)
this.ini.arr.add(item)
}
var stack = Stack()
stack.pushPush(1)
stack.pushPush(2)
print(stack.popPop())
print(stack.peekPeek())
stack.popPop()
print(stack.isEmptyIsEmpty())</langsyntaxhighlight>
 
{{out}}
Line 2,289 ⟶ 2,494:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :stack [] #lists used to be stacks in DV
 
push-to stack 1
Line 2,300 ⟶ 2,505:
 
if stack: #empty lists are falsy
error #this stack should be empty now!</langsyntaxhighlight>
 
=={{header|Diego}}==
Diego has a <code>stack</code> object and posit:
<syntaxhighlight lang="diego">set_ns(rosettacode)_me();
 
add_stack({int},a)_values(1..4); // 1,2,3,4 (1 is first/bottom, 4 is last/top)
with_stack(a)_pop(); // 1,2,3
with_stack(a)_push()_v(5,6); // 1,2,3,5,6
 
add_var({int},b)_value(7);
with_stack(a)_push[b]; // 1,2,3,5,6,7
 
with_stack(a)_pluck()_at(2); // callee will return `with_stack(a)_err(pluck invalid with stack);`
 
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 2,325 ⟶ 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 2,356 ⟶ 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 :
<langsyntaxhighlight lang="lisp">
; build stack [0 1 ... 9 (top)] from a list
(list->stack (iota 10) 'my-stack)
Line 2,381 ⟶ 2,642:
⛔ error: #|user| : unbound variable : my-stack
(stack-top 'my-stack) → 7
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
STACK_ON_ARRAY
Line 2,428 ⟶ 2,689:
 
end
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
<langsyntaxhighlight lang="elena">public program()
{
var stack := new system'collections'Stack();
stack.push:(2);
var isEmpty := stack.Length == 0;
Line 2,442 ⟶ 2,703:
item := stack.pop()
}</langsyntaxhighlight>
 
=={{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 2,466 ⟶ 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 2,492 ⟶ 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 2,508 ⟶ 2,769:
 
Pull (BookStack)?
***** Exception: Stack Underflow</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Stack do
def new, do: []
Line 2,523 ⟶ 2,784:
def top([h|_]), do: h
end</langsyntaxhighlight>
 
Example:
Line 2,543 ⟶ 2,804:
=={{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 2,555 ⟶ 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 2,572 ⟶ 2,833:
false
7> stack:empty(stack:new()).
true</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
Line 2,578 ⟶ 2,839:
 
A list-based immutable stack type could be implemented like this:
<langsyntaxhighlight lang="fsharp">type Stack<'a> //'//(workaround for syntax highlighting problem)
(?items) =
let items = defaultArg items []
Line 2,597 ⟶ 2,858:
let (x, stack3) = stack2.Pop()
printfn "%d" x
printfn "%A" (stack3.IsEmpty())</langsyntaxhighlight>
 
=={{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 2,613 ⟶ 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 2,630 ⟶ 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 floating point numbers.
<langsyntaxhighlight lang="fortran">module mod_stack
 
implicit none
Line 2,744 ⟶ 3,005:
end do
call my_stack%clearStack()
end program main</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
===Delphi adaptation===
Example taken and adapted from the Delphi entry.
<langsyntaxhighlight lang="pascal">program Stack;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
Line 2,771 ⟶ 3,032:
lStack.Free;
end;
end.</langsyntaxhighlight>
<pre>
Output:
Line 2,779 ⟶ 3,040:
===Object version from scratch===
{{works with|Free Pascal|version 3.2.0 }}
<syntaxhighlight lang="pascal">
<lang Pascal>
PROGRAM StackObject.pas;
{$IFDEF FPC}
Line 2,801 ⟶ 3,062:
What happens after retrieving the variable is TBD by you.
 
https://www.freepascal.org/advantage.var
(*)
 
Line 2,939 ⟶ 3,201:
END.
 
</langsyntaxhighlight>JPD 2021/07/03
 
Output:
Line 2,971 ⟶ 3,233:
=={{header|FreeBASIC}}==
We first use a macro to define a generic Stack type :
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' stack_rosetta.bi
Line 3,055 ⟶ 3,317:
End Function
#EndMacro</langsyntaxhighlight>
 
We now use this type to create a Stack of Dog instances :
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "stack_rosetta.bi"
Line 3,106 ⟶ 3,368:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 3,122 ⟶ 3,384:
=={{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>
<langsyntaxhighlight lang="frink">a = new array
a.push[1]
a.push[2]
a.peek[]
while ! a.isEmpty[]
println[a.pop[]]</langsyntaxhighlight>
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/*
Stack, in Genie, with GLib double ended Queues
Line 3,149 ⟶ 3,411:
print "stack size before clear: " + stack.get_length().to_string()
stack.clear()
print "After clear, stack.is_empty(): " + stack.is_empty().to_string()</langsyntaxhighlight>
 
{{out}}
Line 3,161 ⟶ 3,423:
=={{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 3,223 ⟶ 3,485:
fmt.Println("nothing to pop")
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,233 ⟶ 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 3,239 ⟶ 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 3,275 ⟶ 3,585:
assert stack.empty
 
try { stack.pop() } catch (NoSuchElementException e) { println e.message }</langsyntaxhighlight>
 
{{out}}
Line 3,288 ⟶ 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 3,305 ⟶ 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 3,328 ⟶ 3,638:
 
nonEmpty :: Stack a ()
nonEmpty = empty >>= flip when (fail "Stack empty")</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 3,335 ⟶ 3,645:
The programmer is free to use any or all of the list processing functions on any problem.
The following illustrates typical stack usage:
<langsyntaxhighlight Iconlang="icon">procedure main()
stack := [] # new empty stack
push(stack,1) # add item
Line 3,350 ⟶ 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 3,374 ⟶ 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}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 LET N=255 ! Size of stack
110 NUMERIC STACK(1 TO N)
120 LET PTR=1
Line 3,407 ⟶ 3,717:
300 DEF TOP=STACK(PTR-1)
310 CALL PUSH(3):CALL PUSH(5)
320 PRINT POP+POP</langsyntaxhighlight>
 
=={{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 3,445 ⟶ 3,755:
stack.pop();
}
}</langsyntaxhighlight>
{{out}}
<pre>New stack empty? true
Line 3,457 ⟶ 3,767:
 
Alternatively, you might implement a stack yourself...
<langsyntaxhighlight lang="java">public class Stack{
private Node first = null;
public boolean isEmpty(){
Line 3,485 ⟶ 3,795:
}
}
}</langsyntaxhighlight>
{{works with|Java|1.5}}
<langsyntaxhighlight lang="java5">public class Stack<T>{
private Node first = null;
public boolean isEmpty(){
Line 3,515 ⟶ 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 3,532 ⟶ 3,842:
this.empty = function() {return this.data.length == 0}
this.peek = function() {return this.data[this.data.length - 1]}
}</langsyntaxhighlight>
Here's an example using the revealing module pattern instead of prototypes.
<langsyntaxhighlight lang="javascript">
function makeStack() {
var stack = [];
Line 3,559 ⟶ 3,869:
};
}
</syntaxhighlight>
</lang>
 
=={{header|Jsish}}==
From Javascript entry. Being ECMAScript, Jsi supports stack primitives as part of the Array methods.
<langsyntaxhighlight lang="javascript">/* Stack, is Jsish */
var stack = [];
puts('depth:', stack.length);
Line 3,577 ⟶ 3,887:
if (stack.length) printf('not '); printf('empty\n');
 
puts('depth:', stack.length);</langsyntaxhighlight>
 
{{out}}
Line 3,589 ⟶ 3,899:
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}}==
Line 3,594 ⟶ 3,987:
 
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]
Line 3,601 ⟶ 3,994:
@show length(stack) # 2
@show empty!(stack) # []
@show isempty(stack) # true</langsyntaxhighlight>
 
=={{header|K}}==
<langsyntaxhighlight Klang="k">stack:()
push:{stack::x,stack}
pop:{r:*stack;stack::1_ stack;r}
Line 3,629 ⟶ 4,022:
empty[]
1
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Rather than use the java.util.Stack<E> class, we will write our own simple Stack<E> class for this task:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class Stack<E> {
Line 3,677 ⟶ 4,070:
println(e.message)
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,689 ⟶ 4,082:
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 3,704 ⟶ 4,140:
pop . s. cr # 2 [ 1 ]
pop drop
empty? . # -1</langsyntaxhighlight>
 
=={{header|Lasso}}==
Lasso Arrays natively supports push and pop.
 
<langsyntaxhighlight Lassolang="lasso">local(a) = array
 
#a->push('a')
Line 3,718 ⟶ 4,154:
#a->pop // b
#a->pop // a
#a->pop // null</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
global stack$
stack$=""
Line 3,760 ⟶ 4,196:
empty =(stack$="")
end function
</syntaxhighlight>
</lang>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- parent script "Stack"
 
property _tos
Line 3,785 ⟶ 4,221:
on empty (me)
return voidP(me.peek())
end</langsyntaxhighlight>
 
=={{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 3,811 ⟶ 4,247:
 
:- end_object.
</syntaxhighlight>
</lang>
 
=={{header|LOLCODE}}==
{{trans|UNIX Shell}}
<langsyntaxhighlight lang="lolcode">HAI 2.3
HOW IZ I Init YR Stak
Stak HAS A Length ITZ 0
Line 3,850 ⟶ 4,286:
IM OUTTA YR Loop
 
KTHXBYE</langsyntaxhighlight>
 
{{Out}}
Line 3,860 ⟶ 4,296:
=={{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">
<lang M2000 Interpreter>
Module Checkit {
a=Stack
Line 3,882 ⟶ 4,318:
}
Checkit
</syntaxhighlight>
</lang>
 
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).
Line 3,889 ⟶ 4,325:
Return/Execution stack is hidden and different from stack of values.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Read a, b
Line 3,917 ⟶ 4,353:
Print alfa(1,2,3,4)=2.5
 
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">with(stack): # load the package, to allow use of short command names
 
s := stack:-new(a, b):
Line 3,932 ⟶ 4,368:
empty(s);
pop(s);
empty(s);</langsyntaxhighlight>
{{out}}
<pre> c
Line 3,947 ⟶ 4,383:
 
=={{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 3,960 ⟶ 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 3,976 ⟶ 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 4,061 ⟶ 4,497:
end %methods
end</langsyntaxhighlight>
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> myLIFO = LIFOQueue(1,'fish',2,'fish','red fish','blue fish')
myLIFO =
Line 4,092 ⟶ 4,528:
ans =
 
0</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">/* lists can be used as stacks; Maxima provides pop and push */
 
load(basic)$
Line 4,105 ⟶ 4,541:
 
emptyp(a);
length(a);</langsyntaxhighlight>
 
=={{header|Mercury}}==
Line 4,111 ⟶ 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 4,143 ⟶ 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.
Line 4,154 ⟶ 4,590:
 
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}}==
<langsyntaxhighlight MiniScriptlang="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
Line 4,169 ⟶ 4,617:
else
print "Stack is empty"
end if</langsyntaxhighlight>
{{out}}
<pre>
Line 4,180 ⟶ 4,628:
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">class Stack
declare internalList
 
Line 4,202 ⟶ 4,650:
return len(internalList) = 0
end
end</langsyntaxhighlight>
 
=={{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 4,239 ⟶ 4,687:
stack.Length == 0
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* NetRexx ************************************************************
* 13.08.2013 Walter Pachl translated from REXX version 2
**********************************************************************/
Line 4,283 ⟶ 4,731:
 
method empty(stk) static
Return stk[0]=0</langsyntaxhighlight>
{{out}}
<pre>
Line 4,299 ⟶ 4,747:
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.
 
<langsyntaxhighlight Nimlang="nim">type Stack[T] = distinct seq[T]
 
func initStack[T](initialSize = 32): Stack[T] =
Line 4,340 ⟶ 4,788:
echo s.top
s.mtop = 5
echo s.top</langsyntaxhighlight>
 
{{out}}
Line 4,350 ⟶ 4,798:
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<langsyntaxhighlight lang="oberon2">
MODULE Stacks;
IMPORT
Line 4,417 ⟶ 4,865:
Test
END Stacks.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,426 ⟶ 4,874:
</pre>
{{works with|AOS}}
<langsyntaxhighlight lang="oberon2">
MODULE Stacks; (** AUTHOR ""; PURPOSE ""; *)
 
Line 4,510 ⟶ 4,958:
END Test;
END Stacks.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,520 ⟶ 4,968:
=={{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 4,535 ⟶ 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 4,556 ⟶ 5,004:
method is_empty =
lst = []
end</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 4,562 ⟶ 5,010:
Stack is already defined at startup.
 
<langsyntaxhighlight Oforthlang="oforth">ListBuffer Class new: Stack
Stack method: push self add ;
Stack method: pop self removeLast ;
Stack method: top self last ;</langsyntaxhighlight>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth">: testStack
| s |
Stack new ->s
Line 4,578 ⟶ 5,026:
s pop println
s pop println
s isEmpty ifTrue: [ "Stack is empty" println ] ;</langsyntaxhighlight>
 
{{out}}
Line 4,591 ⟶ 5,039:
=={{header|Ol}}==
Simplest stack can be implemented using 'cons' and 'uncons' primitives.
<langsyntaxhighlight lang="scheme">
(define stack #null)
(print "stack is: " stack)
Line 4,634 ⟶ 5,082:
(print "stack: " stack)
(print "is stack empty: " (eq? stack #null))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,669 ⟶ 5,117:
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!').
 
<langsyntaxhighlight lang="scheme">
(fork-server 'stack (lambda ()
(let this ((me '()))
Line 4,707 ⟶ 5,155:
(loop))))
(print "done.")
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,732 ⟶ 5,180:
=={{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 4,739 ⟶ 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 4,764 ⟶ 5,212:
 
f
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
A thread-safe, list-based stack. Implemented as a module:
<langsyntaxhighlight lang="oz">functor
export
New
Line 4,798 ⟶ 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 4,819 ⟶ 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 4,877 ⟶ 5,325:
PopFromStack := node^.data;
dispose(node);
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
Perl comes prepared to treat its arrays 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|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
I felt it would be helpful to contrast simple, naieve and proper implementations.<br>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
v1: simple, but limited to a single stack
<span style="color: #000080;font-style:italic;">-- comparing a simple implementation against using the builtins:</span>
<lang Phix>sequence stack = {}
<span style="color: #004080;">sequence</span> <span style="color: #000000;">stack</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
 
procedure push(object what)
<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>
stack = append(stack,what)
<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>
end procedure
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
 
function pop()
<span style="color: #008080;">function</span> <span style="color: #000000;">pop_</span><span style="color: #0000FF;">()</span>
object what = stack[$]
<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>
stack = stack[1..$-1]
<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>
return what
<span style="color: #008080;">return</span> <span style="color: #000000;">what</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
function empty()
<span style="color: #008080;">function</span> <span style="color: #000000;">empty_</span><span style="color: #0000FF;">()</span>
return length(stack)=0
<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>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
?empty() -- 1
<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>
push(5)
<span style="color: #000000;">push_</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
?empty() -- 0
<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>
push(6)
<span style="color: #000000;">push_</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
?pop() -- 6
<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>
?pop() -- 5
<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>
?empty() -- 1</lang>
<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>
v2: naieve, multiple stacks but slightly awkward calling convention
<lang Phix>function push(sequence stack, object what)
<span style="color: #0000FF;">?</span><span style="color: #008000;">"===builtins==="</span>
stack = append(stack,what)
<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>
return stack
end function
<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>
function pop(sequence stack)
<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>
object what = stack[$]
<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>
stack = stack[1..$-1]
<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>
return {stack,what}
<span style="color: #000080;font-style:italic;">--?peep(sid) -- 6 (leaving it there)</span>
end function
<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>
function empty(sequence stack)
<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>
return length(stack)=0
<!--</syntaxhighlight>-->
end function
Note you get true/false rather than 1/0 under pwa/p2js (use printf(%t) for consistent results)
 
sequence stack = {}
?empty(stack) -- 1
stack = push(stack,5)
?empty(stack) -- 0
stack = push(stack,6)
integer top
{stack,top} = pop(stack)
?top -- 6
{stack,top} = pop(stack)
?top -- 5
?empty(stack) -- 1</lang>
v3: multiple stacks, better calling convention
<lang Phix>sequence stacks = {}
integer freelist = 0
 
function new_stack()
integer res = freelist
if res!=0 then
freelist = stacks[freelist]
stacks[res] = {}
else
stacks = append(stacks,{})
res = length(stacks)
end if
return res
end function
 
procedure free_stack(integer sid)
stacks[sid] = freelist
freelist = sid
end procedure
 
procedure push(integer sid, object what)
stacks[sid] = append(stacks[sid],what)
end procedure
 
function pop(integer sid)
object res = stacks[sid][$]
stacks[sid] = stacks[sid][1..$-1]
return res
end function
 
function empty(integer sid)
return length(stacks[sid])=0
end function
 
integer sid = new_stack()
?empty(sid) -- 1
push(sid,5)
?empty(sid) -- 0
push(sid,6)
?pop(sid) -- 6
?pop(sid) -- 5
?empty(sid) -- 1
free_stack(sid)</lang>
v1 and v2 are thread-safe as long as only one thread is using a particular stack.
full thread-safety for v3 would require something similar to new_dict, see docs.
 
=={{header|PHP}}==
PHP arrays behave like a stack:
<langsyntaxhighlight lang="php">$stack = array();
 
empty( $stack ); // true
Line 4,995 ⟶ 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 5,022 ⟶ 5,413:
other things contains a stack.
 
<syntaxhighlight lang="pike">
<lang Pike>
object s = ADT.Stack();
s->push("a");
Line 5,029 ⟶ 5,420:
s->top(), s->pop(), s->pop());
s->reset(); // Empty the stack
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,036 ⟶ 5,427:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* Any controlled variable may behave as a stack. */
 
declare s float controlled;
Line 5,074 ⟶ 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 5,088 ⟶ 5,479:
=false
[] empty?
=true</langsyntaxhighlight>
 
=={{header|PowerShell}}==
A new stack:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$stack = New-Object -TypeName System.Collections.Stack
# or
$stack = [System.Collections.Stack] @()
</syntaxhighlight>
</lang>
Push some stuff on the stack:
<syntaxhighlight lang="powershell">
<lang PowerShell>
1, 2, 3, 4 | ForEach-Object {$stack.Push($_)}
</syntaxhighlight>
</lang>
Show stack as a string:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$stack -join ", "
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,110 ⟶ 5,501:
</pre>
Pop the top level of the stack:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$stack.Pop()
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,118 ⟶ 5,509:
</pre>
Show stack as a string:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$stack -join ", "
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,126 ⟶ 5,517:
</pre>
Get a copy of the top level of the stack:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$stack.Peek()
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,134 ⟶ 5,525:
</pre>
The stack:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$stack
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 5,146 ⟶ 5,537:
=={{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 5,156 ⟶ 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 5,198 ⟶ 5,589:
While Not Empty_LIFO()
Debug Pop_LIFO()
Wend</langsyntaxhighlight>
 
{{out}}
Line 5,211 ⟶ 5,602:
The faster and Pythonic way is using a deque (available from 2.4).
A regular list is a little slower.
<langsyntaxhighlight 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 5,227 ⟶ 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 5,240 ⟶ 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:
<syntaxhighlight lang ="python">while not stack.empty():</langsyntaxhighlight>
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.
 
Line 5,254 ⟶ 5,645:
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.
 
<langsyntaxhighlight Quackerylang="quackery">[ size 1 = ] is isempty ( s --> b )
 
[ stack ] is mystack ( --> s )
Line 5,268 ⟶ 5,659:
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"</langsyntaxhighlight>
 
{{out}}
Line 5,289 ⟶ 5,680:
{{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 5,342 ⟶ 5,733:
stack$pop()
# Error in get("pop", env = stack, inherits = TRUE)(stack, ...) :
# can't pop from an empty list</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 5,348 ⟶ 5,739:
Quick functional version:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(define stack '())
Line 5,354 ⟶ 5,745:
(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 5,367 ⟶ 5,758:
(define (empty? stack)
(null? (stack-items stack)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 5,373 ⟶ 5,764:
 
Raku still has the stack functions from Perl 5, but now they also can be accessed by object notation:
<syntaxhighlight lang="raku" perl6line>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</langsyntaxhighlight>
 
=={{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"
URL: http://rosettacode.org/wiki/Stack
Line 5,421 ⟶ 5,812:
assert ['test = v/pop]
assert ['a = v/pop]
assert [not v/empty]</langsyntaxhighlight>
Sample run:
<pre>Simple integers:
Line 5,437 ⟶ 5,828:
 
=={{header|Retro}}==
<langsyntaxhighlight Retrolang="retro">: stack ( n"- ) create 0 , allot ;
: push ( na- ) dup ++ dup @ + ! ;
: pop ( a-n ) dup @ over -- + @ ;
Line 5,451 ⟶ 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 5,461 ⟶ 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 5,505 ⟶ 5,896:
 
empty: Procedure Expose stk.
Return stk.0=0</langsyntaxhighlight>
{{out}}
<pre>
Line 5,518 ⟶ 5,909:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Stack
 
Line 5,536 ⟶ 5,927:
see "Pop: stack is empty" + nl
ok
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,550 ⟶ 5,941:
</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 5,626 ⟶ 6,023:
end
alias inspect to_s
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby">p s = Stack.new # => Stack[]
p s.empty? # => true
p s.size # => 0
Line 5,646 ⟶ 6,043:
p s = Stack[:a, :b, :c] # => Stack[:a, :b, :c]
p s << :d # => Stack[:a, :b, :c, :d]
p s.pop # => :d</langsyntaxhighlight>
 
Just meeting the requirements of a push, pop and empty method:
<langsyntaxhighlight lang="ruby">require 'forwardable'
 
class Stack
Line 5,660 ⟶ 6,057:
def_delegators :@stack, :push, :pop, :empty?
end
</syntaxhighlight>
</lang>
(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 5,704 ⟶ 6,101:
FUNCTION mt$()
stackEnd = 0
END FUNCTION</langsyntaxhighlight>
{{out}}
<pre>Pushed A stack has 1
Line 5,720 ⟶ 6,117:
One could just use a vector (<code>Vec<T></code>) which is part of the standard library
 
<langsyntaxhighlight lang="rust">fn main() {
let mut stack = Vec::new();
stack.push("Element1");
Line 5,731 ⟶ 6,128:
assert_eq!(Some("Element1"), stack.pop());
assert_eq!(None, stack.pop());
}</langsyntaxhighlight>
 
===Simple implementation===
Simply uses a singly-linked list.
<langsyntaxhighlight lang="rust">type Link<T> = Option<Box<Frame<T>>>;
 
pub struct Stack<T> {
Line 5,843 ⟶ 6,240:
}
}
}</langsyntaxhighlight>
 
=={{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 5,879 ⟶ 6,276:
return stack.is_empty;
end;
end;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="sather">class MAIN is
main is
s ::= #STACK{INT};
Line 5,894 ⟶ 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:
<langsyntaxhighlight Scalalang="scala">class Stack[T] {
private var items = List[T]()
 
Line 5,915 ⟶ 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.
<langsyntaxhighlight lang="scala">import collection.mutable.{ Stack => Stak }
 
class Stack[T] extends Stak[T] {
Line 5,926 ⟶ 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 5,938 ⟶ 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 5,956 ⟶ 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 5,999 ⟶ 6,396:
writeln(pop(s) = 10);
writeln(empty(s));
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">put () into stack
repeat with each item of 1 .. 10
push it into stack
Line 6,010 ⟶ 6,407:
pop stack
put it
end repeat</langsyntaxhighlight>
 
=={{header|Sidef}}==
Using a built-in array:
<langsyntaxhighlight lang="ruby">var stack = [];
stack.push(42); # pushing
say stack.pop; # popping
say stack.is_empty; # is_emtpy?</langsyntaxhighlight>
 
Creating a Stack class:
<langsyntaxhighlight lang="ruby">class Stack(stack=[]) {
method pop { stack.pop };
method push(item) { stack.push(item) };
Line 6,029 ⟶ 6,426:
stack.push(42);
say stack.pop; # => 42
say stack.empty; # => true</langsyntaxhighlight>
 
=={{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 6,054 ⟶ 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:
<langsyntaxhighlight lang="smalltalk">
s := Stack new.
s push: 1.
Line 6,065 ⟶ 6,462:
s pop.
s top. "2"
</syntaxhighlight>
</lang>
 
=={{header|Standard ML}}==
Line 6,071 ⟶ 6,468:
The signature for a module supplying a stack interface, with a couple added functions.
 
<langsyntaxhighlight lang="sml">signature STACK =
sig
type 'a stack
Line 6,086 ⟶ 6,483:
val map : ('a -> 'b) -> 'a stack -> 'b stack
val app : ('a -> unit) -> 'a stack -> unit
end</langsyntaxhighlight>
 
An implementation of the <code>STACK</code> signature, using immutable lists.
 
<langsyntaxhighlight lang="sml">structure Stack :> STACK =
struct
type 'a stack = 'a list
Line 6,111 ⟶ 6,508:
fun map f st = List.map f st
fun app f st = List.app f st
end</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 6,118 ⟶ 6,515:
=={{header|Swift}}==
Generic stack.
<langsyntaxhighlight Swiftlang="swift">struct Stack<T> {
var items = [T]()
var empty:Bool {
Line 6,143 ⟶ 6,540:
println(stack.peek())
stack.pop()
println(stack.empty)</langsyntaxhighlight>
{{out}}
<pre>
Line 6,152 ⟶ 6,549:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
processor Stack
@: $;
Line 6,192 ⟶ 6,589:
' -> !OUT::write
'$myStack::empty;' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,205 ⟶ 6,602:
=={{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 6,235 ⟶ 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 6,246 ⟶ 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 6,259 ⟶ 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}}==
Line 6,274 ⟶ 6,682:
 
Here's a simple single-stack solution:
<langsyntaxhighlight lang="sh">init() {
if [[ -n $KSH_VERSION ]]; then
set -A stack
Line 6,306 ⟶ 6,714:
while ! empty; do
pop
done</langsyntaxhighlight>
 
{{Out}}
Line 6,317 ⟶ 6,725:
You can generalize it to multiple stacks with some judicious use of the twin evils of pass-by-name and <tt>eval</tt>:
 
<langsyntaxhighlight lang="sh">init_stack() {
if [[ -n $KSH_VERSION ]]; then
eval 'set -A '"$1"
Line 6,348 ⟶ 6,756:
while ! empty mystack; do
pop mystack
done</langsyntaxhighlight>
 
{{Out}}
Line 6,359 ⟶ 6,767:
=={{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 6,395 ⟶ 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 6,417 ⟶ 6,825:
.Pop
End With
End Sub</langsyntaxhighlight>
{{out}}
<pre>
Line 6,431 ⟶ 6,839:
=={{header|VBScript}}==
===Stack class===
<langsyntaxhighlight lang="vb">class stack
dim tos
dim stack()
Line 6,486 ⟶ 6,894:
wscript.echo s.pop
if s.stackempty then exit for
next</langsyntaxhighlight>
{{out}} (changes every time)
<pre>-1
Line 6,510 ⟶ 6,918:
0.7055475</pre>
===Using an ArrayList.===
<langsyntaxhighlight lang="vb">' Stack Definition - VBScript
Option Explicit
Line 6,548 ⟶ 6,956:
Function empty_(s)
empty_ = s.Count = 0
End Function 'empty_ </langsyntaxhighlight>
{{out}}
<pre>
Line 6,561 ⟶ 6,969:
</pre>
 
=={{header|V (Vlang)}}==
<langsyntaxhighlight lang="go">const (
max_depth = 256
)
Line 6,614 ⟶ 7,022:
stack.pop() or { return }
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Stack is empty? Yes
Line 6,629 ⟶ 7,037:
Stacks as user-defined objects backed by a list.
 
<langsyntaxhighlight lang="wart">def (stack)
(tag 'stack nil)
 
Line 6,639 ⟶ 7,047:
 
def (empty? s) :case (isa stack s)
(empty? rep.s)</langsyntaxhighlight>
 
Example usage:
Line 6,665 ⟶ 7,073:
{{libheader|Wren-seq}}
This uses the Stack class in the above module.
<langsyntaxhighlight ecmascriptlang="wren">import "./seq" for Stack
 
var s = Stack.new()
Line 6,677 ⟶ 7,085:
s.clear()
System.print("Stack cleared")
System.print("Is stack now empty? %((s.isEmpty) ? "yes" : "no")")</langsyntaxhighlight>
 
{{out}}
Line 6,690 ⟶ 7,098:
 
=={{header|X86 Assembly}}==
<langsyntaxhighlight lang="x86asm">
; x86_64 linux nasm
 
Line 6,773 ⟶ 7,181:
mov rdi, 1
syscall
</syntaxhighlight>
</lang>
 
=={{header|XLISP}}==
This is a fairly straightforward implementation, representing a stack as a linked list inside an object.
<langsyntaxhighlight lang="lisp">(define-class stack
(instance-variables vals))
 
Line 6,793 ⟶ 7,201:
 
(define-method (stack 'emptyp)
(null vals))</langsyntaxhighlight>
A sample REPL session:
<langsyntaxhighlight lang="lisp">; Loading 'stack.lsp'
[1] (define st (stack 'new))
 
Line 6,817 ⟶ 7,225:
 
#T
[8] </langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int Stack(100), SP;
 
Line 6,848 ⟶ 7,256:
while not Empty do [IntOut(0, Pop); ChOut(0, ^ )];
CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 6,857 ⟶ 7,265:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">limit = 1000
dim stack(limit)
 
Line 6,897 ⟶ 7,305:
 
print "Pop ", pop()
</syntaxhighlight>
</lang>
=={{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 z80Z80'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</langsyntaxhighlight>
 
 
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.
<langsyntaxhighlight lang="z80">push af
push bc
push de
push hl</langsyntaxhighlight>
 
Popping is very similar. To properly pop values, they must be popped in the reverse order they were pushed.
<langsyntaxhighlight lang="z80">pop hl
pop de
pop bc
pop af</langsyntaxhighlight>
 
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:
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
<langsyntaxhighlight 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</langsyntaxhighlight>
 
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.
Line 6,930 ⟶ 7,338:
 
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:
<langsyntaxhighlight lang="z80"> ADD SP,&FE ;subtract two from the stack pointer. Remember that the stack grows "down" in memory.</langsyntaxhighlight>
 
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 6,940 ⟶ 7,350:
fcn empty {(not stack.len())}
var [proxy] isEmpty = empty;
}</langsyntaxhighlight>
{{out}}
<pre>
1

edit