Queue/Definition: Difference between revisions

m
 
(76 intermediate revisions by 40 users not shown)
Line 10:
 
Operations:
:*   push   (aka ''enqueue'')    - add element
:*   pop     (aka ''dequeue'')    - pop first element
:*   empty                             - return truth value when empty
 
 
Line 25:
{{Template:See also lists}}
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">T FIFO
[Int] contents
 
F push(item)
.contents.append(item)
F pop()
R .contents.pop(0)
F empty()
R .contents.empty
 
V f = FIFO()
f.push(3)
f.push(2)
f.push(1)
L !f.empty()
print(f.pop())</syntaxhighlight>
 
{{out}}
<pre>
3
2
1
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program defqueue64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ NBMAXIELEMENTS, 100
/*******************************************/
/* Structures */
/********************************************/
/* example structure for value of item */
.struct 0
value_ident: // ident
.struct value_ident + 8
value_value1: // value 1
.struct value_value1 + 8
value_value2: // value 2
.struct value_value2 + 8
value_fin:
/* example structure for queue */
.struct 0
queue_ptdeb: // begin pointer of item
.struct queue_ptdeb + 8
queue_ptfin: // end pointer of item
.struct queue_ptfin + 8
queue_stvalue: // structure of value item
.struct queue_stvalue + (value_fin * NBMAXIELEMENTS)
queue_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEmpty: .asciz "Empty queue. \n"
szMessNotEmpty: .asciz "Not empty queue. \n"
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "Ident : @ value 1 : @ value 2 : @ \n" // message result
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
Queue1: .skip queue_fin // queue memory place
stItem: .skip value_fin // value item memory place
sZoneConv: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrQueue1 // queue structure address
bl isEmpty
cmp x0,#0
beq 1f
ldr x0,qAdrszMessEmpty
bl affichageMess // display message empty
b 2f
1:
ldr x0,qAdrszMessNotEmpty
bl affichageMess // display message not empty
2:
// init item 1
ldr x0,qAdrstItem
mov x1,#1
str x1,[x0,#value_ident]
mov x1,#11
str x1,[x0,#value_value1]
mov x1,#12
str x1,[x0,#value_value2]
ldr x0,qAdrQueue1 // queue structure address
ldr x1,qAdrstItem
bl pushQueue // add item in queue
cmp x0,#-1 // error ?
beq 99f
// init item 2
ldr x0,qAdrstItem
mov x1,#2
str x1,[x0,#value_ident]
mov x1,#21
str x1,[x0,#value_value1]
mov x1,#22
str x1,[x0,#value_value2]
ldr x0,qAdrQueue1 // queue structure address
ldr x1,qAdrstItem
bl pushQueue // add item in queue
cmp x0,#-1
beq 99f
ldr x0,qAdrQueue1 // queue structure address
bl isEmpty
cmp x0,#0 // not empty
beq 3f
ldr x0,qAdrszMessEmpty
bl affichageMess // display message empty
b 4f
3:
ldr x0,qAdrszMessNotEmpty
bl affichageMess // display message not empty
4:
ldr x0,qAdrQueue1 // queue structure address
bl popQueue // return address item
cmp x0,#-1 // error ?
beq 99f
mov x2,x0 // save item pointer
ldr x0,[x2,#value_ident]
ldr x1,qAdrsZoneConv // conversion ident
bl conversion10S // decimal conversion
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first @ character
mov x5,x0
ldr x0,[x2,#value_value1]
ldr x1,qAdrsZoneConv // conversion value 1
bl conversion10S // decimal conversion
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at Second @ character
mov x5,x0
ldr x0,[x2,#value_value2]
ldr x1,qAdrsZoneConv // conversion value 2
bl conversion10S // decimal conversion
mov x0,x5
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at third @ character
bl affichageMess // display message final
b 4b // loop
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrQueue1: .quad Queue1
qAdrstItem: .quad stItem
qAdrszMessError: .quad szMessError
qAdrszMessEmpty: .quad szMessEmpty
qAdrszMessNotEmpty: .quad szMessNotEmpty
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
 
/******************************************************************/
/* test if queue empty */
/******************************************************************/
/* x0 contains the address of queue structure */
/* x0 returns 0 if not empty, 1 if empty */
isEmpty:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x1,[x0,#queue_ptdeb] // begin pointer
ldr x2,[x0,#queue_ptfin] // begin pointer
cmp x1,x2
bne 1f
mov x0,#1 // empty queue
b 2f
1:
mov x0,#0 // not empty
2:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
 
/******************************************************************/
/* add item in queue */
/******************************************************************/
/* x0 contains the address of queue structure */
/* x1 contains the address of item */
pushQueue:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
add x2,x0,#queue_stvalue // address of values structure
ldr x3,[x0,#queue_ptfin] // end pointer
add x2,x2,x3 // free address of queue
ldr x4,[x1,#value_ident] // load ident item
str x4,[x2,#value_ident] // and store in queue
ldr x4,[x1,#value_value1] // idem
str x4,[x2,#value_value1]
ldr x4,[x1,#value_value2]
str x4,[x2,#value_value2]
add x3,x3,#value_fin
cmp x3,#value_fin * NBMAXIELEMENTS
beq 99f
str x3,[x0,#queue_ptfin] // store new end pointer
b 100f
99:
mov x0,#-1 // error
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
 
/******************************************************************/
/* pop queue */
/******************************************************************/
/* x0 contains the address of queue structure */
popQueue:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x1,x0 // control if empty queue
bl isEmpty
cmp x0,#1 // yes -> error
beq 99f
mov x0,x1
ldr x1,[x0,#queue_ptdeb] // begin pointer
add x2,x0,#queue_stvalue // address of begin values item
add x2,x2,x1 // address of item
add x1,x1,#value_fin
str x1,[x0,#queue_ptdeb] // store nex begin pointer
mov x0,x2 // return pointer item
b 100f
99:
mov x0,#-1 // error
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
 
</syntaxhighlight>
{{output}}
<pre>
Empty queue.
Not empty queue.
Ident : +1 value 1 : +11 value 2 : +12
Ident : +2 value 1 : +21 value 2 : +22
Error detected !!!!.
</pre>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun enqueue (x xs)
(cons x xs))
 
Line 40 ⟶ 316:
 
(defun empty (xs)
(endp xs))</langsyntaxhighlight>
 
=={{header|Action!}}==
===Static memory===
Following solution uses fixed array as a buffer for the queue.
<syntaxhighlight lang="action!">DEFINE MAXSIZE="200"
BYTE ARRAY queue(MAXSIZE)
BYTE queueFront=[0],queueRear=[0]
 
BYTE FUNC IsEmpty()
IF queueFront=queueRear THEN
RETURN (1)
FI
RETURN (0)
 
PROC Push(BYTE v)
BYTE rear
 
rear=queueRear+1
IF rear=MAXSIZE THEN
rear=0
FI
IF rear=queueFront THEN
PrintE("Error: queue is full!")
Break()
FI
queue(queueRear)=v
queueRear=rear
RETURN
 
BYTE FUNC Pop()
BYTE v
 
IF IsEmpty() THEN
PrintE("Error: queue is empty!")
Break()
FI
v=queue(queueFront)
queueFront==+1
IF queueFront=MAXSIZE THEN
queueFront=0
FI
RETURN (v)
 
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Queue is empty")
ELSE
PrintE("Queue 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===
Following solution uses module for dynamic memory allocation. 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 QueueNode=[BYTE data PTR nxt]
 
QueueNode POINTER queueFront,queueRear
 
BYTE FUNC IsEmpty()
IF queueFront=0 THEN
RETURN (1)
FI
RETURN (0)
 
PROC Push(BYTE v)
QueueNode POINTER node
 
node=Alloc(NODE_SIZE)
node.data=v
node.nxt=0
IF IsEmpty() THEN
queueFront=node
ELSE
queueRear.nxt=node
FI
queueRear=node
RETURN
 
BYTE FUNC Pop()
QueueNode POINTER node
BYTE v
IF IsEmpty() THEN
PrintE("Error: queue is empty!")
Break()
FI
 
node=queueFront
v=node.data
queueFront=node.nxt
Free(node,NODE_SIZE)
RETURN (v)
 
PROC TestIsEmpty()
IF IsEmpty() THEN
PrintE("Queue is empty")
ELSE
PrintE("Queue 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)
queueFront=0
queueRear=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 the program is intentional.
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Queue_array.png Screenshot from Atari 8-bit computer]
<pre>
Queue is empty
Push: 10
Queue is not empty
Push: 31
Pop: 10
Queue is not empty
Push: 5
Pop: 31
Pop: 5
Pop: Error: queue is empty!
 
RETURN
Error: 128
</pre>
 
=={{header|Ada}}==
Line 46 ⟶ 503:
 
The interface specification for a FIFO is described in the package specification.
<langsyntaxhighlight lang="ada">generic
type Element_Type is private;
package Fifo is
Line 65 ⟶ 522:
Next : Fifo_Ptr := null;
end record;
end Fifo;</langsyntaxhighlight>
The FIFO implementation is described in the package body:
<langsyntaxhighlight lang="ada">with Ada.Unchecked_Deallocation;
 
package body Fifo is
Line 115 ⟶ 572:
end Is_Empty;
 
end Fifo;</langsyntaxhighlight>
A "main" procedure for this program is:
<langsyntaxhighlight lang="ada">with Fifo;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 133 ⟶ 590:
Put_Line(Integer'Image(Val));
end loop;
end Fifo_Test;</langsyntaxhighlight>
The following implementation produces equivalent functionality by deriving from the standard Ada Container type Doubly_Linked_Lists.
 
This example needs fewer lines of code on the part of the application programmer, but the implementation is less efficient than the previous example. Each element has all the data members needed for a doubly linked list. It also links in all the functionality of a doubly linked list. Most of that functionality is unneeded in a FIFO.
<langsyntaxhighlight lang="ada">
with Ada.Containers.Doubly_Linked_Lists;
generic
Line 151 ⟶ 608:
Type Fifo_Type is new List with null record;
end Generic_Fifo;
</syntaxhighlight>
</lang>
<langsyntaxhighlight lang="ada">
package body Generic_Fifo is
Line 177 ⟶ 634:
end Pop;
end Generic_Fifo;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">with Generic_Fifo;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 194 ⟶ 651:
Put_Line(Integer'Image(Val));
end loop;
end Generic_Fifo_Test;</langsyntaxhighlight>
The function Is_Empty is inherited from the Lists type.
 
Line 200 ⟶ 657:
 
If we wish for the reader to read every value written by the writer we must synchronize the tasks. The writer can only write a new value when the buffer contains a stale value. The reader can only read a value when the value is fresh. This synchronization forces the two tasks to run at the same speed.
<langsyntaxhighlight lang="ada">generic
type Element_Type is private;
package Synchronous_Fifo is
Line 210 ⟶ 667:
Is_New : Boolean := False;
end Fifo;
end Synchronous_Fifo;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">package body Synchronous_Fifo is
 
----------
Line 241 ⟶ 698:
end Fifo;
 
end Synchronous_Fifo;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">with Synchronous_Fifo;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 297 ⟶ 754:
Writer.Stop;
Reader.Stop;
end Synchronous_Fifo_Test;</langsyntaxhighlight>
Another choice is to cause the two tasks to run independently. The writer can write whenever it is scheduled. The reader reads whenever it is scheduled, after the writer writes the first valid value.
 
Line 303 ⟶ 760:
 
In a fully asynchronous system the reader only samples the values written by the writer. There is no control over the number of values not sampled by the reader, or over the number of times the reader reads the same value.
<langsyntaxhighlight lang="ada">generic
type Element_Type is private;
package Asynchronous_Fifo is
Line 313 ⟶ 770:
Valid : Boolean := False;
end Fifo;
end Asynchronous_Fifo;</langsyntaxhighlight>
You may notice that the protected type specification is remarkably similar to the synchronous example above. The only important difference is that Push is declared to be an Entry in the synchronous example while it is a procedure in the asynchronous example. Entries only execute when their boundary condition evaluates to TRUE. Procedures execute unconditionally.
<langsyntaxhighlight lang="ada">package body Asynchronous_Fifo is
 
----------
Line 344 ⟶ 801:
end Fifo;
 
end Asynchronous_Fifo;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">with Asynchronous_Fifo;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 386 ⟶ 843:
Put_Line(Integer'Image(Val));
end select;
end loop;<syntaxhighlight lang="ada">
end Reader;
begin
Line 392 ⟶ 849:
Writer.Stop;
Reader.Stop;
end Asynchronous_Fifo_Test;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68|Revision 1 - one extension to language used - PRAGMA READ - a non standard feature similar to C's #include directive.}}
{{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/queue_base.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
CO REQUIRES:
MODE OBJLINK = STRUCT(
Line 469 ⟶ 927:
self IS obj queue empty;
 
SKIP</langsyntaxhighlight>'''See also:''' [[Queue/Usage#ALGOL_68|Queue/Usage]]
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% define a Queue type that will hold StringQueueElements %
record StringQueue ( reference(StringQueueElement) front, back );
Line 522 ⟶ 980:
while not isEmptyStringQueue( q ) do write( popString( q ) )
end
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 530 ⟶ 988:
barney
</pre>
 
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="applesoftbasic"> 0 DEF FN E(MPTY) = SP = FIRST
10 GOSUB 150EMPTY
20 LET A$ = "A": GOSUB 100PUSH
30 LET A$ = "B": GOSUB 100PUSH
40 GOSUB 150EMPTY
50 GOSUB 120PULL FIRST
60 GOSUB 120PULL FIRST
70 GOSUB 150EMPTY
80 GOSUB 120PULL FIRST
90 END
100 PRINT "PUSH "A$
110 LET S$(SP) = A$:SP = SP + 1: RETURN
120 GOSUB 130: PRINT "POP "A$: RETURN
130 IF FN E(0) THEN PRINT "POPPING FROM EMPTY QUEUE";: STOP
140 A$ = S$(FI): FI = FI + 1 : RETURN
150 PRINT "EMPTY? " MID$ ("YESNO",4 ^ FN E(0),3): RETURN</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program defqueue.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
 
.equ NBMAXIELEMENTS, 100
 
/*******************************************/
/* Structures */
/********************************************/
/* example structure for value of item */
.struct 0
value_ident: @ ident
.struct value_ident + 4
value_value1: @ value 1
.struct value_value1 + 4
value_value2: @ value 2
.struct value_value2 + 4
value_fin:
/* example structure for queue */
.struct 0
queue_ptdeb: @ begin pointer of item
.struct queue_ptdeb + 4
queue_ptfin: @ end pointer of item
.struct queue_ptfin + 4
queue_stvalue: @ structure of value item
.struct queue_stvalue + (value_fin * NBMAXIELEMENTS)
queue_fin:
 
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEmpty: .asciz "Empty queue. \n"
szMessNotEmpty: .asciz "Not empty queue. \n"
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .ascii "Ident :" @ message result
sMessIdent: .fill 11, 1, ' '
.ascii " value 1 :"
sMessValue1: .fill 11, 1, ' '
.ascii " value 2 :"
sMessValue2: .fill 11, 1, ' '
.asciz "\n"
 
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
Queue1: .skip queue_fin @ queue memory place
stItem: .skip value_fin @ value item memory place
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrQueue1 @ queue structure address
bl isEmpty
cmp r0,#0
beq 1f
ldr r0,iAdrszMessEmpty
bl affichageMess @ display message empty
b 2f
1:
ldr r0,iAdrszMessNotEmpty
bl affichageMess @ display message not empty
2:
@ init item 1
ldr r0,iAdrstItem
mov r1,#1
str r1,[r0,#value_ident]
mov r1,#11
str r1,[r0,#value_value1]
mov r1,#12
str r1,[r0,#value_value2]
 
ldr r0,iAdrQueue1 @ queue structure address
ldr r1,iAdrstItem
bl pushQueue @ add item in queue
cmp r0,#-1 @ error ?
beq 99f
@ init item 2
ldr r0,iAdrstItem
mov r1,#2
str r1,[r0,#value_ident]
mov r1,#21
str r1,[r0,#value_value1]
mov r1,#22
str r1,[r0,#value_value2]
 
ldr r0,iAdrQueue1 @ queue structure address
ldr r1,iAdrstItem
bl pushQueue @ add item in queue
cmp r0,#-1
beq 99f
ldr r0,iAdrQueue1 @ queue structure address
bl isEmpty
cmp r0,#0 @ not empty
beq 3f
ldr r0,iAdrszMessEmpty
bl affichageMess @ display message empty
b 4f
3:
ldr r0,iAdrszMessNotEmpty
bl affichageMess @ display message not empty
 
4:
ldr r0,iAdrQueue1 @ queue structure address
bl popQueue @ return address item
cmp r0,#-1 @ error ?
beq 99f
mov r2,r0 @ save item pointer
ldr r0,[r2,#value_ident]
ldr r1,iAdrsMessIdent @ display ident
bl conversion10 @ decimal conversion
ldr r0,[r2,#value_value1]
ldr r1,iAdrsMessValue1 @ display value 1
bl conversion10 @ decimal conversion
ldr r0,[r2,#value_value2]
ldr r1,iAdrsMessValue2 @ display value 2
bl conversion10 @ decimal conversion
ldr r0,iAdrszMessResult
bl affichageMess @ display message
b 4b @ loop
 
99:
@ error
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
 
iAdrQueue1: .int Queue1
iAdrstItem: .int stItem
iAdrszMessError: .int szMessError
iAdrszMessEmpty: .int szMessEmpty
iAdrszMessNotEmpty: .int szMessNotEmpty
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessIdent: .int sMessIdent
iAdrsMessValue1: .int sMessValue1
iAdrsMessValue2: .int sMessValue2
/******************************************************************/
/* test if queue empty */
/******************************************************************/
/* r0 contains the address of queue structure */
isEmpty:
push {r1,r2,lr} @ save registres
ldr r1,[r0,#queue_ptdeb] @ begin pointer
ldr r2,[r0,#queue_ptfin] @ begin pointer
cmp r1,r2
moveq r0,#1 @ empty queue
movne r0,#0 @ not empty
pop {r1,r2,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* add item in queue */
/******************************************************************/
/* r0 contains the address of queue structure */
/* r1 contains the address of item */
pushQueue:
push {r1-r4,lr} @ save registres
add r2,r0,#queue_stvalue @ address of values structure
ldr r3,[r0,#queue_ptfin] @ end pointer
add r2,r3 @ free address of queue
ldr r4,[r1,#value_ident] @ load ident item
str r4,[r2,#value_ident] @ and store in queue
ldr r4,[r1,#value_value1] @ idem
str r4,[r2,#value_value1]
ldr r4,[r1,#value_value2]
str r4,[r2,#value_value2]
add r3,#value_fin
cmp r3,#value_fin * NBMAXIELEMENTS
moveq r0,#-1 @ error
beq 100f
str r3,[r0,#queue_ptfin] @ store new end pointer
100:
pop {r1-r4,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* pop queue */
/******************************************************************/
/* r0 contains the address of queue structure */
popQueue:
push {r1,r2,lr} @ save registres
mov r1,r0 @ control if empty queue
bl isEmpty
cmp r0,#1 @ yes -> error
moveq r0,#-1
beq 100f
mov r0,r1
ldr r1,[r0,#queue_ptdeb] @ begin pointer
add r2,r0,#queue_stvalue @ address of begin values item
add r2,r1 @ address of item
add r1,#value_fin
str r1,[r0,#queue_ptdeb] @ store nex begin pointer
mov r0,r2 @ return pointer item
100:
pop {r1,r2,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ previous position
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#' '
3:
strb r1,[r3,r4]
add r4,#1
cmp r4,#LGZONECAL @ end
ble 3b
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} @ save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 @ r2 <- r2 >> 2
mov r1, r0, LSR #31 @ r1 <- r0 >> 31
add r0, r2, r1 @ r0 <- r2 + r1
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2-r4}
bx lr @ return
 
</syntaxhighlight>
{{output}}
Empty queue.
 
Not empty queue.
 
Ident :1 value 1 :11 value 2 :12
 
Ident :2 value 1 :21 value 2 :22
 
Error detected !!!!.
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="arturo">define :queue [][
init: [
this\items: []
]
]
 
empty?: function [this :queue][
zero? this\items
]
 
push: function [this :queue, item][
this\items: this\items ++ item
]
 
pop: function [this :queue][
ensure -> not? empty? this
result: this\items\0
this\items: remove.index this\items 0
return result
]</syntaxhighlight>
 
=={{header|ATS}}==
 
A common theme in these examples is that there is no runtime error for popping from an empty queue. Instead, you simply cannot compile a program that tries to pop from an empty queue. The type of a queue depends on its size, and you will get a type error if that size is not proven to be nonzero.
 
One way to get such a proof is with an assertion that calls the ''is_empty'' predicate. But the compiler does not insert that check for you, and the example programs do not need it.
 
=== A linear linked list as a queue ===
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)
 
#define ATS_DYNLOADFLAG 0
 
#include "share/atspre_staload.hats"
 
staload UN = "prelude/SATS/unsafe.sats"
 
(*------------------------------------------------------------------*)
 
vtypedef queue_vt (vt : vt@ype+, n : int) =
(* A list that forms the queue, and a pointer to its last node. *)
@(list_vt (vt, n), ptr)
 
#define NIL list_vt_nil ()
#define :: list_vt_cons
 
fn {}
queue_vt_nil {vt : vt@ype}
() :
queue_vt (vt, 0) =
@(NIL, the_null_ptr)
 
fn {}
queue_vt_is_empty
{n : int}
{vt : vt@ype}
(q : !queue_vt (vt, n)) :
[is_empty : bool | is_empty == (n == 0)]
bool is_empty =
case+ q.0 of
| NIL => true
| _ :: _ => false
 
fn {vt : vt@ype}
queue_vt_enqueue
{n : int}
(q : queue_vt (vt, n),
x : vt) :
(* Returns the new queue. *)
[m : int | 1 <= m; m == n + 1]
queue_vt (vt, m) =
let
val @(lst, tail_ptr) = q
prval _ = lemma_list_vt_param lst
in
case+ lst of
| ~ NIL =>
let
val lst = x :: NIL
val tail_ptr = $UN.castvwtp1{ptr} lst
in
@(lst, tail_ptr)
end
| _ :: _ =>
let
val old_tail = $UN.castvwtp0{list_vt (vt, 1)} tail_ptr
val+ @ (hd :: tl) = old_tail
 
(* Extend the list by one node, at its tail end. *)
val new_tail : list_vt (vt, 1) = x :: NIL
val tail_ptr = $UN.castvwtp1{ptr} new_tail
prval _ = $UN.castvwtp0{void} tl
val _ = tl := new_tail
 
prval _ = fold@ old_tail
prval _ = $UN.castvwtp0{void} old_tail
 
(* Let us cheat and simply *assert* (rather than prove) that
the list has grown by one node. *)
val lst = $UN.castvwtp0{list_vt (vt, n + 1)} lst
in
@(lst, tail_ptr)
end
end
 
(* The dequeue routine simply CANNOT BE CALLED with an empty queue.
It requires a queue of type queue_vt (vt, n) where n is positive. *)
fn {vt : vt@ype}
queue_vt_dequeue
{n : int | 1 <= n}
(q : queue_vt (vt, n)) :
(* Returns a tuple: the dequeued element and the new queue. *)
[m : int | 0 <= m; m == n - 1]
@(vt, queue_vt (vt, m)) =
case+ q.0 of
| ~ (x :: lst) => @(x, @(lst, q.1))
 
(* queue_vt is a linear type that must be freed. *)
extern fun {vt : vt@ype}
queue_vt$element_free : vt -> void
fn {vt : vt@ype}
queue_vt_free {n : int}
(q : queue_vt (vt, n)) :
void =
let
fun
loop {n : nat} .<n>. (lst : list_vt (vt, n)) : void =
case+ lst of
| ~ NIL => begin end
| ~ (hd :: tl) =>
begin
queue_vt$element_free<vt> hd;
loop tl
end
prval _ = lemma_list_vt_param (q.0)
in
loop (q.0)
end
 
(*------------------------------------------------------------------*)
(* An example: a queue of nonlinear strings. *)
 
vtypedef strq_vt (n : int) = queue_vt (string, n)
 
fn {} (* A parameterless template, for efficiency. *)
strq_vt_nil () : strq_vt 0 =
queue_vt_nil ()
 
fn {} (* A parameterless template, for efficiency. *)
strq_vt_is_empty {n : int} (q : !strq_vt n) :
[is_empty : bool | is_empty == (n == 0)] bool is_empty =
queue_vt_is_empty<> q
 
fn
strq_vt_enqueue {n : int} (q : strq_vt n, x : string) :
[m : int | 1 <= m; m == n + 1] strq_vt m =
queue_vt_enqueue<string> (q, x)
 
fn (* Impossible to... VVVVVV ...call with an empty queue. *)
strq_vt_dequeue {n : int | 1 <= n} (q : strq_vt n) :
[m : int | 0 <= m; m == n - 1] @(string, strq_vt m) =
queue_vt_dequeue<string> q
 
fn
strq_vt_free {n : int} (q : strq_vt n) : void =
let
implement
queue_vt$element_free<string> x =
(* A nonlinear string will be allowed to leak. (It might be
collected as garbage, however.) *)
begin end
in
queue_vt_free<string> q
end
 
macdef qnil = strq_vt_nil ()
overload iseqz with strq_vt_is_empty
overload << with strq_vt_enqueue
overload pop with strq_vt_dequeue
overload free with strq_vt_free
 
implement
main0 () =
{
val q = qnil
val _ = println! ("val q = qnil")
val _ = println! ("iseqz q = ", iseqz q)
val _ = println! ("val q = q << \"one\" << \"two\" << \"three\"")
val q = q << "one" << "two" << "three"
val _ = println! ("iseqz q = ", iseqz q)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val q = q << \"four\"")
val q = q << "four"
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("iseqz q = ", iseqz q)
//val (x, q) = pop q // If you uncomment this you cannot compile!
val _ = free q
}
 
(*------------------------------------------------------------------*)</syntaxhighlight>
 
{{out}}
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW queues-postiats.dats -lgc && ./a.out
val q = qnil
iseqz q = true
val q = q << "one" << "two" << "three"
iseqz q = false
val (x, q) = pop q
x = one
val (x, q) = pop q
x = two
val q = q << "four"
val (x, q) = pop q
x = three
val (x, q) = pop q
x = four
iseqz q = true</pre>
 
=== A nonlinear circular queue with an automatically resizing buffer ===
 
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)
(*
 
The following implementation prevents us from trying to dequeue
from an empty queue. A program that tries to do so cannot be
compiled.
 
However, it does not prove there are no buffer overruns.
 
It contains much embedded C code, for which I used the quick and
dirty "$extfcall" method.
 
*)
(*------------------------------------------------------------------*)
 
#define ATS_DYNLOADFLAG 0
 
#include "share/atspre_staload.hats"
 
(*------------------------------------------------------------------*)
 
(* For the demonstration, let us set BUFSIZE_INITIAL to the minimum
possible. If you try setting it any lower, though, you cannot
compile the program. *)
#define BUFSIZE_INITIAL 2
 
prval _ = prop_verify {2 <= BUFSIZE_INITIAL} ()
 
datatype queue_t (t : t@ype+,
n : int) =
| queue_t_empty (t, 0) of (size_t, ptr)
| {1 <= n}
queue_t_nonempty (t, n) of
(size_t, ptr, size_t n, size_t, size_t)
 
fn
queue_t_new {t : t@ype}
() : queue_t (t, 0) =
queue_t_empty (i2sz 0, the_null_ptr)
 
fn
queue_t_is_empty
{n : int}
{t : t@ype}
(q : queue_t (t, n)) :
[b : bool | b == (n == 0)]
bool b =
case+ q of
| queue_t_empty _ => true
| queue_t_nonempty _ => false
 
fn {t : t@ype}
queue_t_enqueue
{n : int}
(q : queue_t (t, n),
x : t) :
[m : int | 1 <= m; m == n + 1]
queue_t (t, m) =
let
macdef tsz = sizeof<t>
macdef zero = i2sz 0
macdef one = i2sz 1
var xvar = x
val px = addr@ xvar
in
case+ q of
| queue_t_empty (bufsize, pbuf) =>
if bufsize = zero then
let
val bufsize = i2sz BUFSIZE_INITIAL
val pbuf =
$extfcall (ptr, "ATS_MALLOC", bufsize * tsz)
val _ = $extfcall (ptr, "memcpy", pbuf, px, tsz)
in
queue_t_nonempty (bufsize, pbuf, one, zero, one)
end
else
let
val _ = $extfcall (ptr, "memcpy", pbuf, px, tsz)
in
queue_t_nonempty (bufsize, pbuf, one, zero, one)
end
| queue_t_nonempty (bufsize, pbuf, n, ihead, itail) =>
if n = bufsize then
let
(* Resize the buffer. *)
val bsize = i2sz 2 * bufsize
val _ = assertloc (itail = ihead) (* Sanity check. *)
val _ = assertloc (bufsize < bsize) (* Overflow? *)
val p = $extfcall (ptr, "ATS_MALLOC", bsize * tsz)
val _ = $extfcall (ptr, "memcpy", p,
ptr_add<t> (pbuf, ihead),
(bufsize - ihead) * tsz)
val _ = $extfcall (ptr, "memcpy",
ptr_add<t> (p, bufsize - ihead),
pbuf, ihead * tsz)
val _ = $extfcall (ptr, "memcpy", ptr_add<t> (p, n),
px, tsz)
in
queue_t_nonempty (bsize, p, succ n, zero, succ n)
end
else
let
val _ = $extfcall (ptr, "memcpy", ptr_add<t> (pbuf, itail),
px, tsz)
val itail = (succ itail) mod bufsize
in
queue_t_nonempty (bufsize, pbuf, succ n, ihead, itail)
end
end
 
fn {t : t@ype}
queue_t_dequeue
{n : int | 1 <= n}
(q : queue_t (t, n)) :
[m : int | m == n - 1]
@(t, queue_t (t, m)) =
let
macdef tsz = sizeof<t>
macdef zero = i2sz 0
macdef one = i2sz 1
var xvar : t
val px = addr@ xvar
val queue_t_nonempty (bufsize, pbuf, n, ihead, itail) = q
val _ = $extfcall (ptr, "memcpy", px, ptr_add<t> (pbuf, ihead),
tsz)
val ihead = (succ ihead) mod bufsize
val x = $UNSAFE.cast{t} xvar
in
if n = one then
@(x, queue_t_empty (bufsize, pbuf))
else
@(x, queue_t_nonempty (bufsize, pbuf, pred n, ihead, itail))
end
 
(*------------------------------------------------------------------*)
(* An example: a queue of strings. *)
 
vtypedef strq_t (n : int) = queue_t (string, n)
 
fn
strq_t_new () : strq_t 0 =
queue_t_new ()
 
fn {} (* A parameterless template, for efficiency. *)
strq_t_is_empty {n : int} (q : strq_t n) :
[is_empty : bool | is_empty == (n == 0)] bool is_empty =
queue_t_is_empty q
 
fn
strq_t_enqueue {n : int} (q : strq_t n, x : string) :
[m : int | 1 <= m; m == n + 1] strq_t m =
queue_t_enqueue<string> (q, x)
 
fn (* Impossible to... VVVVVV ...call with an empty queue. *)
strq_t_dequeue {n : int | 1 <= n} (q : strq_t n) :
[m : int | 0 <= m; m == n - 1] @(string, strq_t m) =
queue_t_dequeue<string> q
 
overload strq with strq_t_new
overload iseqz with strq_t_is_empty
overload << with strq_t_enqueue
overload pop with strq_t_dequeue
 
implement
main0 () =
{
val q = strq ()
val _ = println! ("val q = strq ()")
val _ = println! ("iseqz q = ", iseqz q)
val _ = println! ("val q = q << \"one\" << \"two\" << \"three\"")
val q = q << "one" << "two" << "three"
val _ = println! ("val q = q << \"ett\" << \"två\" << \"tre\"")
val q = q << "ett" << "två" << "tre"
val _ = println! ("iseqz q = ", iseqz q)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val q = q << \"four\"")
val q = q << "four"
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val q = q << \"fyra\"")
val q = q << "fyra"
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("val (x, q) = pop q")
val (x, q) = pop q
val _ = println! ("x = ", x)
val _ = println! ("iseqz q = ", iseqz q)
//val (x, q) = pop q // If you uncomment this you cannot compile!
}
 
(*------------------------------------------------------------------*)</syntaxhighlight>
 
{{out}}
<pre>$ patscc -O2 -DATS_MEMALLOC_GCBDW circular_queues-postiats.dats -lgc && ./a.out
val q = strq ()
iseqz q = true
val q = q << "one" << "two" << "three"
val q = q << "ett" << "två" << "tre"
iseqz q = false
val (x, q) = pop q
x = one
val (x, q) = pop q
x = two
val q = q << "four"
val (x, q) = pop q
x = three
val (x, q) = pop q
x = ett
val q = q << "fyra"
val (x, q) = pop q
x = två
val (x, q) = pop q
x = tre
val (x, q) = pop q
x = four
val (x, q) = pop q
x = fyra
iseqz q = true</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST
 
MsgBox % "Len = " len("qu") ; Number of entries
Line 562 ⟶ 1,805:
StringReplace %queue%, %queue%, |, |, UseErrorLevel
Return %queue% = "" ? 0 : ErrorLevel+1
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 596 ⟶ 1,840:
return length(q) == 0
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 610 ⟶ 1,854:
</pre>
 
=={{header|BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<syntaxhighlight lang="bbcbasic"> FIFOSIZE = 1000
FOR n = 3 TO 5
PRINT "Push ";n : PROCenqueue(n)
NEXT
PRINT "Pop " ; FNdequeue
PRINT "Push 6" : PROCenqueue(6)
REPEAT
PRINT "Pop " ; FNdequeue
UNTIL FNisempty
PRINT "Pop " ; FNdequeue
END
DEF PROCenqueue(n) : LOCAL f%
DEF FNdequeue : LOCAL f% : f% = 1
DEF FNisempty : LOCAL f% : f% = 2
PRIVATE fifo(), rptr%, wptr%
DIM fifo(FIFOSIZE-1)
CASE f% OF
WHEN 0:
wptr% = (wptr% + 1) MOD FIFOSIZE
IF rptr% = wptr% ERROR 100, "Error: queue overflowed"
fifo(wptr%) = n
WHEN 1:
IF rptr% = wptr% ERROR 101, "Error: queue empty"
rptr% = (rptr% + 1) MOD FIFOSIZE
= fifo(rptr%)
WHEN 2:
= (rptr% = wptr%)
ENDCASE
ENDPROC</syntaxhighlight>
{{out}}
<pre>
Push 3
Push 4
Push 5
Pop 3
Push 6
Pop 4
Pop 5
Pop 6
Pop
Error: queue empty
</pre>
=={{header|Batch File}}==
 
Line 616 ⟶ 1,907:
More complex variations can be written that remove this limitation.
 
<langsyntaxhighlight lang="dos">
@echo off
setlocal enableDelayedExpansion
Line 686 ⟶ 1,977:
for %%N in (!%~1.head!) do set %~2=!%~1.%%N!
exit /b 0
</syntaxhighlight>
</lang>
 
=={{header|BBC BASICBQN}}==
 
{{works with|BBC BASIC for Windows}}
Queues are already straightforward to make in BQN via its convenient builtins. This object is made for demonstration of BQN's object oriented features. It would generally be much simpler to apply the related functions to an array instead of creating a big object.
<lang bbcbasic> FIFOSIZE = 1000
 
<syntaxhighlight lang="bqn">queue ← {
FOR n = 3 TO 5
data ← ⟨⟩
PRINT "Push ";n : PROCenqueue(n)
Push ⇐ {data∾˜↩𝕩}
NEXT
PRINT "Pop " ; FNdequeue{
𝕊𝕩:
PRINT "Push 6" : PROCenqueue(6)
0=≠data ? •Show "Cannot pop from empty queue";
REPEAT
(data↓˜↩¯1)⊢⊑⌽data
PRINT "Pop " ; FNdequeue
}
UNTIL FNisempty
Empty ⇐ {𝕊𝕩: 0=≠data}
PRINT "Pop " ; FNdequeue
Display ⇐ {𝕊𝕩: •Show data}
END
}
 
DEF PROCenqueue(n) : LOCAL f%
q1 ← queue
DEF FNdequeue : LOCAL f% : f% = 1
 
DEF FNisempty : LOCAL f% : f% = 2
•Show q1.Empty@
PRIVATE fifo(), rptr%, wptr%
q1.Push 3
DIM fifo(FIFOSIZE-1)
q1.Push 4
CASE f% OF
q1.Display@
WHEN 0:
•Show q1.Pop@
wptr% = (wptr% + 1) MOD FIFOSIZE
q1.Display@</syntaxhighlight><syntaxhighlight lang="text">1
IF rptr% = wptr% ERROR 100, "Error: queue overflowed"
⟨ 4 3 ⟩
fifo(wptr%) = n
3
WHEN 1:
⟨ 4 ⟩</syntaxhighlight>
IF rptr% = wptr% ERROR 101, "Error: queue empty"
rptr% = (rptr% + 1) MOD FIFOSIZE
= fifo(rptr%)
WHEN 2:
= (rptr% = wptr%)
ENDCASE
ENDPROC</lang>
{{out}}
<pre>
Push 3
Push 4
Push 5
Pop 3
Push 6
Pop 4
Pop 5
Pop 6
Pop
Error: queue empty
</pre>
 
It's also possible to build a queue out of linked node objects, an approach discussed in [https://mlochbaum.github.io/BQN/doc/oop.html#mutability this section] of the BQN documentation. While much slower to traverse, this approach opens up new possibilities, such as constant time deletion and insertion at an arbitrary node, that aren't available with plain arrays.
 
=={{header|Bracmat}}==
Line 740 ⟶ 2,013:
 
No special provision is implemented to "throw and exception" in case you try to dequeue from and empty queue, because, in Bracmat, evaluation of an expression, besides resulting in an evaluated expression, always also either "succeeds" or "fails". (There is, in fact, a third possibility, "ignore", telling Bracmat to close an eye even though an evaluation didn't succeed.) So in the example below, the last dequeue operation fails and the program continues on the right hand side of the bar (<code>|</code>) operator
<langsyntaxhighlight lang="bracmat"> ( queue
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
Line 749 ⟶ 2,022:
)
(empty=.!(its.list):)
)</langsyntaxhighlight>
 
Normally you would seldom use a class as depicted above, because the operations are so simple that you probably use them directly. Bracmat lists allow prepending as well as appending elements, and single elements can be removed from the beginning or from the end of a list.
 
Appending an element to a long list and removing an element from the end of a long list are quite expensive operations, with a cost <i>O</i>(<i>n</i>), where <i>n</i> is the number of elements in the queue.
 
 
=={{header|C}}==
===Dynamic array===
Dynamic array working as a circular buffer.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 810 ⟶ 2,082:
}
return 1;
}</langsyntaxhighlight>
 
===Doubly linked list===
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 856 ⟶ 2,128:
return 1;
}
</syntaxhighlight>
</lang>
 
'''Test code'''
This main function works with both implementions above.
<langsyntaxhighlight lang="c">int main()
{
int i, n;
Line 881 ⟶ 2,153:
 
return 0;
}</langsyntaxhighlight>
 
Of the above two programs, for int types the array method is about twice as fast for the test code given. The doubly linked list is marginally faster than the <code>sys/queue.h</code> below.
Line 888 ⟶ 2,160:
Using the <tt>sys/queue.h</tt>, which is not POSIX.1-2001 (but it is BSD). The example allows to push/pop int values, but instead of <tt>int</tt> one can use <tt>void *</tt> and push/pop any kind of "object" (of course changes to the commodity functions <tt>m_queue</tt> and <tt>m_dequeue</tt> are needed)
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 934 ⟶ 2,206:
if ( l->tqh_first == NULL ) return true;
return false;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
Compatible with C# 3.0 specification, requires System library for exceptions (from either .Net or Mono). A FIFO class in C# using generics and nodes.
<syntaxhighlight lang="csharp">public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
//Uses object initializers to set fields of new node
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}</syntaxhighlight>
 
=={{header|C++}}==
{{works with|g++|4.1.2 20061115 (prerelease) (Debian 4.1.1-21)}}
C++ already has a class <code>queue</code> in the standard library, however the following is a simple implementation based on a singly linkes list. Note that an empty queue is internally represented by <code>head == 0</code>, therefore it doesn't matter that the <code>tail</code> value is invalid in that case.
<langsyntaxhighlight lang="cpp">namespace rosettacode
{
template<typename T> class queue
Line 1,005 ⟶ 2,318:
return head == 0;
}
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
Compatible with C# 3.0 specification, requires System library for exceptions (from either .Net or Mono). A FIFO class in C# using generics and nodes.
<lang csharp>public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
//Uses object initializers to set fields of new node
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}</lang>
 
=={{header|Clojure}}==
Clojure has a built-in persistent FIFO queue which can be accessed by referring to clojure.lang.PersistentQueue/EMPTY. Queues are manipulated similarly to Clojure's stacks using peek and pop.
The "pop" function implies mutating the input, but since Clojure data structures are immutable we use a mutable reference to an immutable data structure; in this case an <tt>atom</tt> holding a vector:
 
<syntaxhighlight lang ="clojure">(defn make-queue []
(atom []))
 
user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY)
(defn enqueue [q x]
#'user/empty-queue
(swap! q conj x))
user=> (def aqueue (atom empty-queue))
 
#'user/aqueue
(defn dequeue [q]
; Check if queue is empty
(if-let [[f & r] (seq @q)]
user=> (empty? @aqueue)
(do (reset! q r) f)
true
(throw (IllegalStateException. "Can't pop an empty queue."))))
; As with other Clojure data structures, you can add items using conj and into
user=> (swap! aqueue conj 1)
user=> (swap! aqueue into [2 3 4])
user=> (pprint @aqueue)
<-(1 2 3 4)-<
; You can read the head of the queue with peek
user=> (peek @aqueue)
1
; You can remove the head producing a new queue using pop
user=> (pprint (pop @aqueue))
<-(2 3 4)-<
; pop returns a new queue, the original is still intact
user=> (pprint @aqueue)
<-(1 2 3 4)-<
; you can treat a queue as a sequence
user=> (into [] @aqueue)
[1 2 3 4]
; but remember that using rest or next converts the queue to a seq. Compare:
user=> (-> @aqueue rest (conj 5) pprint)
(5 2 3 4)
; with:
user=> (-> @aqueue pop (conj 5) pprint)
<-(2 3 4 5)-<
 
</syntaxhighlight>
(defn queue-empty? [q]
(empty? @q))</lang>
 
Here's a link with further documentation [https://admay.github.io/queues-in-clojure/ Queues in Clojure]
The implementation is thread-safe if there is at most one writer thread, i.e. only one thread ever calls <code>dequeue</code> on a given queue.
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# Implement a fifo as an array of arrays, to
# greatly amortize dequeue costs, at some expense of
Line 1,107 ⟶ 2,400:
v = q.dequeue()
console.log v
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,123 ⟶ 2,416:
This defines a queue structure that stores its items in a list, and maintains a tail pointer (i.e., a pointer to the last cons in the list). Note that dequeuing the last item in the queue does not clear the tail pointer—enqueuing into the resulting empty queue will correctly reset the tail pointer.
 
<langsyntaxhighlight lang="lisp">(defstruct (queue (:constructor %make-queue))
(items '() :type list)
(tail '() :type list))
Line 1,148 ⟶ 2,441:
(if (queue-empty-p queue)
(error "Cannot dequeue from empty queue.")
(pop (queue-items queue))))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE Queue;
IMPORT StdLog,Boxes;
Boxes;
 
TYPE
Queue Instance* = POINTER TO LIMITED RECORD
first,last size: LONGINT;
first,last: LONGINT;
queue: POINTER TO ARRAY OF Boxes.Object;
_queue: POINTER TO ARRAY OF Boxes.Box;
END;
END;
PROCEDURE NewQueue*(cap: LONGINT): Queue;
PROCEDURE (self: Instance) Initialize(capacity: LONGINT),NEW;
VAR
BEGIN
q: Queue;
self.size := 0;
BEGIN
NEW(q);q self.first := 0; q.last := 0;
self.last := 0;
NEW(q.queue,cap);
NEW(self._queue,capacity)
RETURN q
END NewQueueInitialize;
PROCEDURE New*(qcapacity: Queue) IsEmpty*(LONGINT): BOOLEAN, NEWInstance;
VAR
aQueue: Instance;
BEGIN
BEGIN
RETURN (q.first = q.last)
NEW(aQueue);aQueue.Initialize(capacity);RETURN aQueue
END IsEmpty;
END New;
PROCEDURE (q: Queue) Push*(o: Boxes.Object),NEW;
PROCEDURE (self: Instance) IsEmpty*(): BOOLEAN, NEW;
VAR
BEGIN
i,j,oldSize,newSize: LONGINT;
RETURN self.size = 0;
queue: POINTER TO ARRAY OF Boxes.Object;
END IsEmpty;
BEGIN
IF q.IsEmpty() THEN
PROCEDURE (self: Instance) Capacity*(): LONGINT, NEW;
q.queue[q.last] := o;
BEGIN
q.last := (q.last + 1) MOD LEN(q.queue)
RETURN LEN(self._queue)
ELSE
END Capacity;
q.queue[q.last] := o;
q.last := (q.last + 1) MOD LEN(q.queue);
PROCEDURE (self: Instance) Size*(): LONGINT, NEW;
IF q.first = q.last THEN
BEGIN
(* grow queue *)
RETURN self.size
newSize := LEN(q.queue) + (LEN(q.queue) DIV 2);
END Size;
(* new queue*)
NEW(queue,newSize);
PROCEDURE (self: Instance) IsFull*(): BOOLEAN, NEW;
(* move data from old queue to new queue *)
BEGIN
i := q.first; j := 0;oldSize := LEN(q.queue) - q.first + q.last;
RETURN self.size = self.Capacity()
WHILE (j < oldSize ) & (j < LEN(queue) - 1) DO
END IsFull;
queue[j] := q.queue[i];
i := (i + 1) MOD LEN(q.queue);INC(j)
PROCEDURE (self: Instance) Push*(b: Boxes.Box), NEW;
END;
VAR
q.queue := queue;q.first := 0;q.last := j
i, j, newCapacity, oldSize: LONGINT;
END
queue: POINTER TO ARRAY OF Boxes.Box;
END;
BEGIN
END Push;
INC(self.size);
self._queue[self.last] := b;
PROCEDURE (q: Queue) Pop*(): Boxes.Object, NEW;
self.last := (self.last + 1) MOD self.Capacity();
VAR
IF self.IsFull() THEN
o: Boxes.Object;
(* grow queue *)
BEGIN
newCapacity := self.Capacity() + (self.Capacity() DIV 2);
ASSERT(~q.IsEmpty());
(* new queue *)
o := q.queue[q.first];
NEW(queue,newCapacity);
q.queue[q.first] := NIL;
(* move data from old to new queue *)
q.first := (q.first + 1) MOD LEN(q.queue);
i := self.first; j := 0; oldSize := self.Capacity() - self.first + self.last;
RETURN o;
WHILE (j < oldSize) & (j < newCapacity - 1) DO
END Pop;
queue[j] := self._queue[i];
 
i := (i + 1) MOD newCapacity;INC(j)
END;
self._queue := queue;self.first := 0;self.last := j
END
END Push;
PROCEDURE (self: Instance) Pop*(): Boxes.Box, NEW;
VAR
b: Boxes.Box;
BEGIN
ASSERT(~self.IsEmpty());
DEC(self.size);
b := self._queue[self.first];
self._queue[self.first] := NIL;
self.first := (self.first + 1) MOD self.Capacity();
RETURN b
END Pop;
END Queue.
</syntaxhighlight>
</lang>
Interface extracted from implementation
<langsyntaxhighlight lang="oberon2">
DEFINITION Queue;
 
IMPORT Boxes;
 
TYPE
Queue Instance = POINTER TO LIMITED RECORD
(qself: QueueInstance) IsEmptyCapacity (): BOOLEANLONGINT, NEW;
(qself: QueueInstance) PopIsEmpty (): Boxes.ObjectBOOLEAN, NEW;
(qself: QueueInstance) PushIsFull (o): Boxes.Object)BOOLEAN, NEW;
(self: Instance) Pop (): Boxes.Box, NEW;
END;
(self: Instance) Push (b: Boxes.Box), NEW;
(self: Instance) Size (): LONGINT, NEW
END;
 
PROCEDURE NewQueueNew (capcapacity: LONGINT): QueueInstance;
 
END Queue.
 
</lang>
</syntaxhighlight>
 
=={{header|Cowgol}}==
 
This code should be put in a file called <code>queue.coh</code>, to be used with the
Cowgol program at [[Queue/Usage]]. The queue is implemented by means of a linked list.
 
<syntaxhighlight lang="cowgol">include "strings.coh";
include "malloc.coh";
 
# Define types. The calling code is expected to provide a QueueData type.
record QueueItem is
data: QueueData;
next: [QueueItem];
end record;
 
record QueueMeta is
head: [QueueItem];
tail: [QueueItem];
end record;
 
typedef Queue is [QueueMeta];
const Q_NONE := 0 as [QueueItem];
 
# Allocate and free the queue datastructure.
sub MakeQueue(): (q: Queue) is
q := Alloc(@bytesof QueueMeta) as Queue;
q.head := Q_NONE;
q.tail := Q_NONE;
end sub;
 
sub FreeQueue(q: Queue) is
var cur := q.head;
while cur != Q_NONE loop
var next := cur.next;
Free(cur as [uint8]);
cur := next;
end loop;
Free(q as [uint8]);
end sub;
 
# Check if queue is empty.
sub QueueEmpty(q: Queue): (r: uint8) is
r := 0;
if q.head == Q_NONE then
r := 1;
end if;
end sub;
 
# Enqueue and dequeue data. Cowgol has no exceptions, so the calling code
# should check QueueEmpty first.
sub Enqueue(q: Queue, d: QueueData) is
var item := Alloc(@bytesof QueueItem) as [QueueItem];
item.data := d;
item.next := Q_NONE;
if q.head == Q_NONE then
q.head := item;
else
q.tail.next := item;
end if;
q.tail := item;
end sub;
 
sub Dequeue(q: Queue): (d: QueueData) is
d := q.head.data;
var cur := q.head;
q.head := q.head.next;
Free(cur as [uint8]);
if q.head == Q_NONE then
q.tail := Q_NONE;
end if;
end sub;</syntaxhighlight>
 
=={{header|D}}==
Line 1,240 ⟶ 2,626:
=={{header|Déjà Vu}}==
This uses a dictionary to have a sort of [[wp:Circular_buffer|circular buffer]] of infinite size.
<langsyntaxhighlight lang="dejavu">queue:
{ :start 0 :end 0 }
 
Line 1,255 ⟶ 2,641:
 
empty q:
= q!start q!end</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.Generics.Collections}}
<syntaxhighlight lang="delphi">program QueueDefinition;
 
{$APPTYPE CONSOLE}
 
uses
System.Generics.Collections;
 
type
TQueue = System.Generics.Collections.TQueue<Integer>;
 
TQueueHelper = class helper for TQueue
function Empty: Boolean;
function Pop: Integer;
procedure Push(const NewItem: Integer);
end;
 
{ TQueueHelper }
 
function TQueueHelper.Empty: Boolean;
begin
Result := count = 0;
end;
 
function TQueueHelper.Pop: Integer;
begin
Result := Dequeue;
end;
 
procedure TQueueHelper.Push(const NewItem: Integer);
begin
Enqueue(NewItem);
end;
 
var
Queue: TQueue;
i: Integer;
 
begin
Queue := TQueue.Create;
 
for i := 1 to 1000 do
Queue.push(i);
 
while not Queue.Empty do
Write(Queue.pop, ' ');
Writeln;
 
Queue.Free;
Readln;
end.
</syntaxhighlight>
=={{header|E}}==
 
Line 1,263 ⟶ 2,701:
Also, according to E design principles, the read and write ends of the queue are separate objects. This has two advantages; first, it implements [http://wiki.erights.org/wiki/POLA POLA] by allowing only the needed end of the queue to be handed out to its users; second, if the reader end is garbage collected the contents of the queue automatically will be as well (rather than accumulating if the writer continues writing).
 
<langsyntaxhighlight lang="e">def makeQueue() {
def [var head, var tail] := Ref.promise()
 
Line 1,289 ⟶ 2,727:
return [reader, writer]
}</langsyntaxhighlight>
=={{header|EasyLang}}==
 
A double-linked list is used, which is implemented via an expandable array.
 
<syntaxhighlight>
prefix qu_
global q[] head tail .
#
proc enq n . .
if tail = 0
head = 1
else
q[tail + 2] = len q[] + 1
.
q[] &= n
q[] &= tail
q[] &= 0
tail = len q[] - 2
.
func deq .
if head = 0
return 0 / 0
.
r = q[head]
old = head
head = q[head + 2]
last = len q[]
prev = q[last - 1]
if prev <> 0
q[prev + 2] = old
.
next = q[last]
if next <> 0
q[next + 1] = old
else
tail = old
.
q[old] = q[last - 2]
q[old + 1] = q[last - 1]
q[old + 2] = q[last]
len q[] -3
if head = len q[] + 1
head = old
.
if head <> 0
q[head + 1] = 0
else
tail = 0
.
return r
.
func empty .
return if head = 0
.
prefix
#
qu_enq 2
qu_enq 5
qu_enq 7
while qu_empty = 0
print qu_deq
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
There is no native queue type in EchoLisp. make-Q implements queues in message passing style, using vector operations. Conversions from-to lists are also provided.
<langsyntaxhighlight lang="lisp">
;; put info string in permanent storage for later use
(info 'make-Q
Line 1,329 ⟶ 2,830:
;; save make-Q
(local-put 'make-Q)
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 36.3x :
<langsyntaxhighlight lang="elena">import extensions.;
templateclass queue :: type<T>
{
array<type>T[] theArray.;
int theTop.;
int theTale.;
explicitconstructor()
[{
theArray := type<>new T[](8).;
theTop := 0.;
theTale := 0.;
]}
bool empty()
= theTop == theTale.;
push(T type:anObjectobject)
[{
if (theTale > theArray length.Length)
[{
theArray := theArray .reallocate(theTale).
].};
theArray[theTale] := anObject.object;
theTale += 1.
]}
typeT pop()
[{
if (theTale == theTop)
[{ InvalidOperationException .new:("Queue is empty"; ).raise() ].};
typeT item := theArray[theTop].;
theTop += 1.;
^ item
]}
}
public program()
program =
{
[
queue<int> q := new queue<int>().;
q .push(1).;
q .push(2).;
q .push(3).;
console .printLine(q .pop().);
console .printLine(q .pop().);
console .printLine(q .pop().);
console .printLine("a queue is ", q .empty; ().iif("empty","not empty")).;
console .print("Trying to pop:").;
try(q pop)
{
q.pop()
}
catch(Exception e)
{
onconsole.printLine(Exception e.Message)
[
console printLine(e message)
]
}
}</syntaxhighlight>
].</lang>
{{out}}
<pre>
Line 1,407 ⟶ 2,910:
This is a generic Queue component based on bi-directional lists. See how in Elisa these [http://jklunder.home.xs4all.nl/elisa/part01/doc080.html lists] are defined.
 
<syntaxhighlight lang="elisa">
<lang Elisa>
component GenericQueue ( Queue, Element );
type Queue;
Line 1,431 ⟶ 2,934:
remove(first(queue.list))];
end component GenericQueue;
</syntaxhighlight>
</lang>
In the following tests we will also show how the internal structure of the queue can be made visible to support debugging.
<syntaxhighlight lang="elisa">
<lang Elisa>
use GenericQueue (QueueofPersons, Person);
type Person = text;
Line 1,463 ⟶ 2,966:
Pull (Q)?
***** Exception: Queue Underflow
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Queue do
def new, do: {Queue, [], []}
Line 1,478 ⟶ 2,981:
def empty?({Queue, [], []}), do: true
def empty?({Queue, _, _}), do: false
end</langsyntaxhighlight>
 
Example:
Line 1,506 ⟶ 3,009:
The standard way to manage fifo in functional programming is to use a pair of list for the fifo queue, one is the input, the other is the output.
When the output is empty just take the input list and reverse it.
<langsyntaxhighlight Erlanglang="erlang">-module(fifo).
-export([new/0, push/2, pop/1, empty/1]).
 
Line 1,518 ⟶ 3,021:
 
empty({fifo, [], []}) -> true;
empty({fifo, _, _}) -> false.</langsyntaxhighlight>
 
Note that there exists a 'queue' module in the standard library handling this for you in the first place
Line 1,524 ⟶ 3,027:
=={{header|ERRE}}==
With ERRE 3.0 you can use a class to define the task (in C-64 version you can simply use procedures):
<langsyntaxhighlight ERRElang="erre">PROGRAM CLASS_DEMO
 
CLASS QUEUE
Line 1,568 ⟶ 3,071:
END FOR
PRINT("* End *")
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>Push 1
Line 1,580 ⟶ 3,083:
Queue is empty!
* End *</pre>
 
=={{header|Factor}}==
{{trans|Java}}
<syntaxhighlight lang="factor">USING: accessors kernel ;
IN: rosetta-code.queue-definition
 
TUPLE: queue head tail ;
TUPLE: node value next ;
 
: <queue> ( -- queue ) queue new ;
: <node> ( obj -- node ) node new swap >>value ;
 
: empty? ( queue -- ? ) head>> >boolean not ;
 
: enqueue ( obj queue -- )
[ <node> ] dip 2dup dup empty?
[ head<< ] [ tail>> next<< ] if tail<< ;
 
: dequeue ( queue -- obj )
dup empty? [ "Cannot dequeue empty queue." throw ] when
[ head>> value>> ] [ head>> next>> ] [ head<< ] tri ;</syntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Queue
{
Line 1,608 ⟶ 3,132:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Forth}}==
This is a FIFO implemented as a circular buffer, as is often found between communicating processes such the interrupt and user parts of a device driver. In practice, the get/put actions would block instead of aborting if the queue is empty/full.
 
<langsyntaxhighlight lang="forth">1024 constant size
create buffer size cells allot
here constant end
Line 1,634 ⟶ 3,158:
empty? abort" buffer empty"
\ begin empty? while pause repeat
head @ @ head @ next head ! -1 used +! ;</langsyntaxhighlight>
 
=== Linked list version ===
Line 1,640 ⟶ 3,164:
Using Forth-2012 structure words and ALLOCATE/FREE. In spirit quite similar to the Java variant below, with one difference: Here we use addresses of fields (not possible in Java), which often makes things simpler than in Java (fewer special cases at boundaries), but in this case it does not. Where the Java version has a special case on enqueue, this version has a special case on dequeue:
 
<langsyntaxhighlight lang="forth">
0
field: list-next
Line 1,683 ⟶ 3,207:
over init-queue then
nip ;
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
Line 1,690 ⟶ 3,214:
See [[FIFO (usage)]] for an example of <code>fifo_nodes</code>
 
<langsyntaxhighlight lang="fortran">module FIFO
use fifo_nodes
! fifo_nodes must define the type fifo_node, with the two field
Line 1,758 ⟶ 3,282:
end function fifo_isempty
 
end module FIFO</langsyntaxhighlight>
 
=={{header|Free Pascal}}==
<syntaxhighlight lang="pascal">program queue;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2); // 1
Write(lQueue.DeQueue:2); // 2
Writeln(lQueue.DeQueue:2); // 3
Assert(lQueue.Count = 0, 'Queue is not empty'); // should be empty
finally
lQueue.Free;
end;
end.</syntaxhighlight>
<pre>
Output:
1 2 3</pre>
 
=={{header|FreeBASIC}}==
We first use a macro to define a generic Queue type :
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' queue_rosetta.bi
Line 1,850 ⟶ 3,400:
Return size
End Function
#EndMacro</langsyntaxhighlight>
We now use this type to create a Queue of Cat instances :
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "queue_rosetta.bi"
Line 1,904 ⟶ 3,454:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,920 ⟶ 3,470:
Error: Attempted to remove 'front' element of an empty queue
</pre>
 
=={{header|Free Pascal}}==
<lang pascal>program queue;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
uses Generics.Collections;
var
lQueue: TQueue<Integer>;
begin
lQueue := TQueue<Integer>.Create;
try
lQueue.EnQueue(1);
lQueue.EnQueue(2);
lQueue.EnQueue(3);
Write(lQueue.DeQueue:2); // 1
Write(lQueue.DeQueue:2); // 2
Writeln(lQueue.DeQueue:2); // 3
Assert(lQueue.Count = 0, 'Queue is not empty'); // should be empty
finally
lQueue.Free;
end;
end.</lang>
<pre>
Output:
1 2 3</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">Enqueue := function(v, x)
Add(v[1], x);
end;
Line 1,981 ⟶ 3,505:
# 6
Dequeue(v);
# fail</langsyntaxhighlight>
 
=={{header|Go}}==
Hard coded to be a queue of strings. Implementation is a circular buffer which grows as needed.
<syntaxhighlight lang="go">
<lang go>
package queue
 
Line 2,041 ⟶ 3,565:
return q.head == q.tail
}
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">class Queue {
private List buffer
 
Line 2,066 ⟶ 3,590:
String toString() { "Queue:${buffer}" }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def q = new Queue()
assert q.empty
 
Line 2,095 ⟶ 3,619:
assert q.empty
try { q.pop() } catch (NoSuchElementException e) { println e }
try { q.dequeue() } catch (NoSuchElementException e) { println e }</langsyntaxhighlight>
 
{{out}}
Line 2,113 ⟶ 3,637:
When the output is empty just take the input list and reverse it.
 
<langsyntaxhighlight lang="haskell">data Fifo a = F [a] [a]
 
emptyFifo :: Fifo a
Line 2,129 ⟶ 3,653:
isEmpty (F [] []) = True
isEmpty _ = False
</syntaxhighlight>
</lang>
 
== Icon and Unicon ==
Line 2,137 ⟶ 3,661:
The following works in both Icon and Unicon:
 
<langsyntaxhighlight lang="icon">
# Use a record to hold a Queue, using a list as the concrete implementation
record Queue(items)
Line 2,172 ⟶ 3,696:
}
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,188 ⟶ 3,712:
Unicon also provides classes:
 
<syntaxhighlight lang="unicon">
<lang Unicon>
# Use a class to hold a Queue, with a list as the concrete implementation
class Queue (items)
Line 2,219 ⟶ 3,743:
}
end
</syntaxhighlight>
</lang>
 
Produces the same output as above.
Line 2,226 ⟶ 3,750:
Object oriented technique, using mutable state:
 
<langsyntaxhighlight Jlang="j">queue_fifo_=: ''
 
pop_fifo_=: verb define
Line 2,241 ⟶ 3,765:
isEmpty_fifo_=: verb define
0=#queue
)</langsyntaxhighlight>
 
Function-level technique, with no reliance on mutable state:
 
<langsyntaxhighlight Jlang="j">pop =: ( {.^:notnull ; }. )@: > @: ] /
push =: ( '' ; ,~ )& > /
tell_atom =: >& {.
Line 2,254 ⟶ 3,778:
onto =: [ ; }.@]
 
notnull =: 0 ~: #</langsyntaxhighlight>
 
See also [[FIFO (usage)#J]]
Line 2,261 ⟶ 3,785:
{{works with|Java|1.5+}}
This task could be done using a LinkedList from java.util, but here is a user-defined version with generics:
<langsyntaxhighlight lang="java">public class Queue<E>{
Node<E> head = null, tail = null;
 
Line 2,300 ⟶ 3,824:
return head == null;
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 2,306 ⟶ 3,830:
 
=== Using built-in Array ===
<langsyntaxhighlight lang="javascript">var fifo = [];
fifo.push(42); // Enqueue.
fifo.push(43);
var x = fifo.shift(); // Dequeue.
alert(x); // 42</langsyntaxhighlight>
 
=== Custom constructor function ===
<langsyntaxhighlight lang="javascript">function FIFO() {
this.data = new Array();
 
Line 2,322 ⟶ 3,846:
this.enqueue = this.push;
this.dequeue = this.pop;
}</langsyntaxhighlight>
 
=={{header|jq}}==
Note that sinceSince jq is a purely functional language, the entityentities chosen to represent queues
representingmust a queue mustsomehow be presented asto anthe inputfunctions tothat operate anyon functionthem.
The approach taken here is to use a JSON object with a key named "queue"
that is to operate on it.
to hold the contents of the queue. This allows us to "pop" a queue by modifying
.queue while returning the popped item in the same object under a different key.
The definition of pop as given below is idiomatic in jq but implies
that popping an empty queue yields [null, []] rather than an error. An
alternative definition, pop_or_error, is also given to illustrate
how an error condition can be generated.
<lang jq># An empty queue:
def fifo: [];
 
There are three possibilities for defining `pop` on an empty queue:
def push(e): [e] + .;
 
# Do not make a special case of it, which in our case would mean that `{queue: []} | pop` would emit `{queue: [], item: null}`
def pop: [.[0], .[1:]];
# Raise an error
# Emit nothing
 
Here (1), is questionable as the queue might contain null, so here we define
def pop_or_error: if length == 0 then error("pop_or_error") else pop end;
`pop_or_error`, which raises an error when given an empty queue, and `pop`, which
emits the empty stream when given an empty queue.
In order to facilitate observing the evolving states of queues during processing,
we use the same `observe` function defined at [[Stack]].
 
<syntaxhighlight lang="jq">
def empty: length == 0;</lang>
# Input: an object
'''Examples''':
# Output: the updated object with .emit filled in from `update|emit`.
<lang jq>fifo | pop # produces [null,[]]
# `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);
 
fifo
| push(42) # enqueue
| push(43) # enqueue
| pop # dequeue
| .[0] # the value
# produces 43
 
def fifo|push(1): as{queue: $q1[]};
 
| fifo|push(2) as $q2
# Is the input an object that represents the empty queue?
| [($q1|pop|.[0]), ($q2|pop|.[0])]
def isempty:
# produces: [1, 2]</lang>
type == "object"
and (.queue | length == 0); # so .queue == null and .queue == [] are equivalent
 
def push(e): .queue += [e];
 
def pop: if isempty then empty else .item = .queue[0] | .queue |= .[1:] end;
 
def pop_or_error: if isempty then error("pop_or_error") else pop end;
 
# Examples
# fifo | pop // "nothing" # produces the string "nothing"
 
fifo
| observe(push(42); "length after pushing: \(.queue | length)" )
| observe(push(43); "length after pushing: \(.queue | length)" )
| pop # dequeue
| .emit, .item
</syntaxhighlight>
'''Output'''
<pre>
length after pushing: 1
length after pushing: 2
42
</pre>
 
=={{header|Julia}}==
Julia provides a variety of queue-like methods for vectors, making the solution to this task rather straightforward. Define a <tt>Queue</tt> in terms of a one dimensional array, and provide its methods using the appropriate vector operations. To adhere to Julia naming conventions, the queue operations are named "push!", "pop!" and "isempty" rather than "push", "pop" and "empty".
<syntaxhighlight lang="julia">
<lang Julia>
typestruct Queue{T}
a::Array{T,1}
end
Line 2,370 ⟶ 3,924:
Base.isempty(q::Queue) = isempty(q.a)
 
function Base.pop!{T}(q::Queue{T}) where {T}
!isempty(q) || error("queue must be non-empty")
pop!(q.a)
end
 
function Base.push!{T}(q::Queue{T}, x::T) where {T}
unshiftpushfirst!(q.a, x)
return q
end
 
function Base.push!{T}(q::Queue{Any}, x::T) where {T}
unshiftpushfirst!(q.a, x)
return q
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,391 ⟶ 3,945:
<pre>
julia> q = Queue()
Queue{Any}({}Any[])
 
julia> isempty(q)
Line 2,397 ⟶ 3,951:
 
julia> push!(q, 1)
Queue{Any}({Any[1}])
 
julia> isempty(q)
Line 2,403 ⟶ 3,957:
 
julia> push!(q, "two")
Queue{Any}({Any["two",1}])
 
julia> push!(q, 3.0)
Queue{Any}({Any[3.0,"two",1}])
 
julia> push!(q, false)
Queue{Any}({Any[false,3.0,"two",1}])
 
julia> pop!(q)
Line 2,425 ⟶ 3,979:
julia> pop!(q)
ERROR: queue must be non-empty
Stacktrace:
in pop! at none:2
[1] error(s::String)
@ Base ./error.jl:33
[2] pop!(q::Queue{Any})
@ Main /tmp/cmdline_1648668849_nacnudus/lines.jl:3
[3] top-level scope
@ REPL[11]:1
</pre>
 
=={{header|Klingphix}}==
<syntaxhighlight lang="klingphix">{ include ..\Utilitys.tlhy }
"..\Utilitys.tlhy" load
 
:push! { l i -- l&i }
0 put
;
:empty? { l -- flag }
len not { len 0 equal }
;
:pop! { l -- l-1 }
empty? (
["Empty"]
[pop swap]
) if
;
( ) { empty queue }
1 push! 2 push! 3 push!
pop! ? pop! ? pop! ? pop! ?
 
"End " input</syntaxhighlight>
{{out}}
<pre>1
2
3
Empty
End</pre>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.util.LinkedList
Line 2,475 ⟶ 4,069:
println(e.message)
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,491 ⟶ 4,085:
{{VI solution|LabVIEW_Queue_Definition.png}}
 
=={{header|Lambdatalk}}==
The APIs of 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 queue.add
{lambda {:v :q}
{let { {_ {A.addlast! :v :q}}}
} ok}}
-> queue.add
 
{def queue.get
{lambda {:q}
{let { {:v {A.first :q}}
{_ {A.subfirst! :q}}
} :v}}}
-> queue.get
 
{def queue.empty?
{lambda {:q}
{A.empty? :q}}}
-> queue.empty?
 
{def Q {A.new}} -> Q []
{queue.add 1 {Q}} -> ok [1]
{queue.add 2 {Q}} -> ok [1,2]
{queue.add 3 {Q}} -> ok [1,2,3]
{queue.get {Q}} -> 1 [2,3]
{queue.add 4 {Q}} -> ok [2,3,4]
{queue.empty? {Q}} -> false
{queue.get {Q}} -> 2 [3,4]
{queue.get {Q}} -> 3 [4]
{queue.get {Q}} -> 4 []
{queue.get {Q}} -> undefined
{queue.empty? {Q}} -> true
 
</syntaxhighlight>
=={{header|Lasso}}==
Definition:
<langsyntaxhighlight lang="lasso">define myqueue => type {
data store = list
Line 2,513 ⟶ 4,143:
 
public isEmpty => (.`store`->size == 0)
}</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="lasso">local(q) = myqueue('a')
#q->isEmpty
// => false
Line 2,529 ⟶ 4,159:
// => true
#q->pop
// => void</langsyntaxhighlight>
 
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">Queue = {}
 
function Queue.new()
Line 2,557 ⟶ 4,186:
function Queue.empty( queue )
return queue.first > queue.last
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
A Stack object can be used as LIFO or FIFO. Data push to bottom of stack. Read pop a value to a variable from top of stack.
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
a=Stack
Line 2,575 ⟶ 4,204:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
Here is a simple implementation of a queue, that works in Matlab and Octave.
<langsyntaxhighlight lang="matlab">myfifo = {};
% push
Line 2,594 ⟶ 4,223:
 
% empty
isempty(myfifo)</langsyntaxhighlight>
 
Below is another solution, that encapsulates the fifo within the object-orientated "class" elements supported by Matlab. For this to work it must be saved in a file named "FIFOQueue.m" in a folder named "@FIFOQueue" in your current Matlab directory.
<langsyntaxhighlight MATLABlang="matlab">%This class impliments a standard FIFO queue.
classdef FIFOQueue
Line 2,678 ⟶ 4,307:
end %methods
end</langsyntaxhighlight>
 
Sample usage:
<langsyntaxhighlight MATLABlang="matlab">>> myQueue = FIFOQueue({'hello'})
myQueue =
Line 2,702 ⟶ 4,331:
>> pop(myQueue)
??? Error using ==> FIFOQueue.FIFOQueue>FIFOQueue.pop at 61
The queue is empty</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">defstruct(queue(in=[], out=[]))$
 
enqueue(x, q) := (q@in: cons(x, q@in), done)$
Line 2,722 ⟶ 4,351:
dequeue(q); /* 3 */
dequeue(q); /* 4 */
dequeue(q); /* fail */</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
This is a fully-featured FIFO queue class definition. In addition to the functions required by the task, it also demonstrates redefining operators for Nanoquery classes by redefining +, *, and =.
<syntaxhighlight lang="nanoquery">class FIFO
declare contents
 
// define constructors for FIFO objects
def FIFO()
this.contents = {}
end
def FIFO(contents)
this.contents = contents
end
 
// define methods for this class
def push(value)
contents.append(value)
end
def pop()
if !this.empty()
value = contents[len(contents) - 1]
contents.remove(len(contents) - 1)
return value
else
// we could throw our own exception here but
// we'll return null instead
return null
end
end
def length()
return len(contents)
end
def extend(itemlist)
contents += itemlist
end
def empty()
return len(contents) = 0
end
 
// define operators for this class
def toString()
return str(contents)
end
def operator+(other)
return this.contents + other.contents
end
def operator*(n)
return this.contents * n
end
def operator=(other)
return this.contents = other.contents
end
end</syntaxhighlight>
 
=={{header|NetRexx}}==
Unlike [[#REXX|Rexx]], NetRexx does not include built&ndash;in support for queues but the language's ability to access the [[Java]] SDK permits use of any number of Java's &quot;Collection&quot; classes.
The following sample implements a stack via the <code>ArrayDeque</code> double&ndash;ended queue.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 2,762 ⟶ 4,444:
 
return
</syntaxhighlight>
</lang>
 
<pre style="height: 20ex; overflow: scroll;">
Line 2,776 ⟶ 4,458:
 
=={{header|Nim}}==
<syntaxhighlight lang ="nim">import queuestype
 
Node[T] = ref object
value: T
next: Node[T]
 
Queue*[T] = object
head, tail: Node[T]
length: Natural
 
func initQueue*[T](): Queue[T] = Queue[T]()
 
func len*(queue: Queue): Natural =
queue.length
 
func isEmpty*(queue: Queue): bool {.inline.} =
queue.len == 0
 
func push*[T](queue: var Queue[T]; value: T) =
let node = Node[T](value: value, next: nil)
if queue.isEmpty: queue.head = node
else: queue.tail.next = node
queue.tail = node
inc queue.length
 
func pop*[T](queue: var Queue[T]): T =
if queue.isEmpty:
raise newException(ValueError, "popping from empty queue.")
result = queue.head.value
queue.head = queue.head.next
dec queue.length
if queue.isEmpty: queue.tail = nil
 
 
when isMainModule:
# defining push & pop (obviously optional)
proc push*[T](q: var TQueue[T]; item: T) =
add(q,item)
proc pop*[T](q: var TQueue[T]): T =
result = dequeue(q)
 
var fifo: TQueue[int] = initQueue[int]()
 
fifo.push(26)
fifo.push(99)
fifo.push(2)
echo( "Fifo size: ", fifo.len())
try:
echo("Popping: ", fifo.pop())
echo( "Popping: ", fifo.pop())
echo( "Popping: ", fifo.pop())
# echo( "Popping: ", fifo.pop()) # popping an empty stack raises [EAssertionFailed]</lang>
echo "Popping: ", fifo.pop()
except ValueError:
echo "Exception catched: ", getCurrentExceptionMsg()</syntaxhighlight>
{{out}}
<pre>Fifo size: 3
Popping: 26
Popping: 99
Popping: 2</pre>
Exception catched: popping from empty queue.</pre>
 
=={{header|OCaml}}==
Line 2,805 ⟶ 4,519:
When the output is empty just take the input list and reverse it.
 
<langsyntaxhighlight lang="ocaml">module FIFO : sig
type 'a fifo
val empty: 'a fifo
Line 2,824 ⟶ 4,538:
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end</langsyntaxhighlight>
 
and a session in the top-level:
 
<langsyntaxhighlight lang="ocaml"># open FIFO;;
# let q = empty ;;
val q : '_a FIFO.fifo = <abstr>
Line 2,855 ⟶ 4,569:
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
Exception: Failure "empty fifo".</langsyntaxhighlight>
 
The standard ocaml library also provides a
Line 2,865 ⟶ 4,579:
If queue is empty, null is returned.
 
<langsyntaxhighlight Oforthlang="oforth">Object Class new: Queue(mutable l)
 
Queue method: initialize ListBuffer new := l ;
Queue method: empty @l isEmpty ;
Queue method: push @l add ;
Queue method: pop @l removeFirst ;</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
This buffer pushes any primitive data (auto converted to strings), and pops strings. The buffer can expand or contract according to usage.
<syntaxhighlight lang="text">
<lang oxygenbasic>
'FIRST IN FIRST OUT
 
'==========
Class Queue
'==========
 
'FIRST IN FIRST OUT
string buf
sys bg,i,le
 
bstring buf 'buffer to hold queue content
method Encodelength(sys ls)
int bg 'buffer base offset
int i 'indexer
int le 'length of buffer
 
method constructor()
====================
buf=""
le=0
bg=0
i=0
end method
 
method destructor()
===================
del buf
le=0
bg=0
i=0
end method
method Encodelength(int ls)
===========================
int p at (i+strptr buf)
p=ls
i+=sizeof int
end method
 
method push(string s)
=====================
ls=len s
int ls=len s
if i+ls+8>le then
buf+=nuls 8000+ls*2 : le=len buf 'expandextend buf
le=len buf
end if
EncodeLength ls 'length of input s
mid buf,i+1,s 'append input s
i+=ls
'EncodeLength ls
end method
 
method GetLengthpopLength() as sysint
=========================
if bg>=i then return -1 'buffer empty
if bg>=i then return -1 'buffer empty
int p at (bg+strptr buf)
int p at (bg+=sizeofstrptr intbuf)
bg+=sizeof int
return p
return p
end method
 
method pop(string *s) as sysint
============================
sys ls=GetLength
int ls=popLength
if ls<0 then s="" : return ls 'empty buffer
s=mid buf,bg+1,ls
bg+=ls
'cleanup buffer
if bg>1e6 then
buf=mid buf,bg+1 : bg=0 : le=len buf : i-=bg 'shrink buf
le=len buf
i-=bg 'shrink buf
bg=0
end if
end method
 
method clear()
==============
buf="" : le="" : bg=0 : i=0
buf=""
le=0
bg=0
i=0
end method
end class 'Queue
 
end class
 
'====
'DEMO
'TEST
'====
 
new Queue fifo
string s
'
Line 2,934 ⟶ 4,680:
fifo.push "Sat on a wall"
'
sysint er
do
er=fifo.pop s
if er then print "(buffer empty)" : exit do
print s
loop
end do
 
</lang>
del fifo
</syntaxhighlight>
 
=={{header|Oz}}==
Line 2,949 ⟶ 4,697:
The implementation is thread-safe if there is only one reader thread. When multiple reader threads exist, it is possible that a value is popped more than once.
 
<langsyntaxhighlight lang="oz">declare
fun {NewQueue}
Stream
Line 2,982 ⟶ 4,730:
{Show {Empty Q}}
{Show {Pop Q}}
{Show {Empty Q}}</langsyntaxhighlight>
 
There is also a [http://www.mozart-oz.org/home/doc/mozart-stdlib/adt/queue.html queue datatype] in the Mozart standard library.
Line 2,993 ⟶ 4,741:
This program should be Standard Pascal compliant (i.e. it doesn't make use of the advanced/non-standard features of FreePascal or GNU Pascal).
 
<langsyntaxhighlight lang="pascal">program fifo(input, output);
 
type
Line 3,093 ⟶ 4,841:
testFifo;
writeln('Testing finished.')
end.</langsyntaxhighlight>
 
 
=={{header|Perl}}==
Lists are a central part of Perl. To implement a FIFO using OO will to many Perl programmers seem a bit awkward.
 
<langsyntaxhighlight lang="perl">use Carp;
sub mypushmy push :prototype(\@@) {my($list,@things)=@_; push @$list, @things}
sub mypopmaypop :prototype(\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty :prototype(@) {not @_}</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="perl">my @fifo=qw(1 2 3 a b c);
 
mypush @fifo, 44, 55, 66;
mypop @fifo for 1 .. 6+3;
mypop @fifo; #empty now</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{Works with|rakudo|2018.03}}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
We could build a new container class to do FIFO pretty easily, but Arrays already do everything needed by a FIFO queue, so it is easier to just compose a Role on the existing Array class.
<span style="color: #004080;">sequence</span> <span style="color: #000000;">queue</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<lang perl6>role FIFO {
method enqueue ( *@values ) { # Add values to queue, returns the number of values added.
<span style="color: #008080;">procedure</span> <span style="color: #000000;">push_item</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">what</span><span style="color: #0000FF;">)</span>
self.push: @values;
<span style="color: #000000;">queue</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">,</span><span style="color: #000000;">what</span><span style="color: #0000FF;">)</span>
return @values.elems;
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
}
method dequeue ( ) { # Remove and return the first value from the queue.
<span style="color: #008080;">function</span> <span style="color: #000000;">pop_item</span><span style="color: #0000FF;">()</span>
# Return Nil if queue is empty.
<span style="color: #004080;">object</span> <span style="color: #000000;">what</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">queue</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
return self.elems ?? self.shift !! Nil;
<span style="color: #000000;">queue</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">queue</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span>
}
<span style="color: #008080;">return</span> <span style="color: #000000;">what</span>
method is-empty ( ) { # Check to see if queue is empty. Returns Boolean value.
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
return self.elems == 0;
}
<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;">queue</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<!--</syntaxhighlight>-->
As of 1.0.2 there are standard builtins for the above, named new_queue(), push(), and queue_empty() respectively, see docs.
 
=={{header|Phixmonti}}==
# Example usage:
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
 
def push /# l i -- l&i #/
my @queue does FIFO;
0 put
enddef
 
def empty? /# l -- flag #/
say @queue.is-empty; # -> Bool::True
len 0 ==
for <A B C> -> $i { say @queue.enqueue: $i } # 1 \n 1 \n 1
enddef
say @queue.enqueue: Any; # -> 1
say @queue.enqueue: 7, 8; # -> 2
say @queue.is-empty; # -> Bool::False
say @queue.dequeue; # -> A
say @queue.elems; # -> 4
say @queue.dequeue; # -> B
say @queue.is-empty; # -> Bool::False
say @queue.enqueue('OHAI!'); # -> 1
say @queue.dequeue until @queue.is-empty; # -> C \n Any() \n [7 8] \n OHAI!
say @queue.is-empty; # -> Bool::True
say @queue.dequeue; # -></lang>
 
def pop /# l -- l-1 #/
=={{header|Phix}}==
empty? if
<lang Phix>sequence queue = {}
"Empty"
else
head swap tail nip swap
endif
enddef
 
procedure push(object what)
queue = append(queue,what)
end procedure
 
( ) /# empty queue #/
function pop()
object what = queue[1]
queue = queue[2..$]
return what
end function
 
1 push 2 push 3 push
function empty()
pop ? pop ? pop ? pop ?</syntaxhighlight>
return length(queue)=0
end function</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">class Fifo {
private $data = array();
public function push($element){
Line 3,185 ⟶ 4,926:
return empty($this->data);
}
}</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight PHPlang="php">$foo = new Fifo();
$foo->push('One');
$foo->enqueue('Two');
Line 3,198 ⟶ 4,939:
echo $foo->pop(); //Prints 'Three'
echo $foo->pop(); //Throws an exception
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
===First variant===
<syntaxhighlight lang="picat">go =>
println("Test 1"),
queue_test1,
nl.
 
empty(Q) => Q = [].
push(Queue, Value) = Q2 =>
Q2 = [Value] ++ Queue.
pop(Q,_) = _, Q==[] ; var(Q) =>
throw $error(empty_queue,pop,'Q'=Q).
pop(Queue,Q2) = Queue.last() =>
Q2 = [Queue[I] : I in 1..Queue.len-1].
 
queue_test1 =>
% create an empty queue
println("Start test 2"),
empty(Q0),
printf("Create queue %w%n%n", Q0),
% add numbers 1 and 2
println("Add numbers 1 and 2 : "),
Q1 = Q0.push(1),
Q2 = Q1.push(2),
% display queue
printf("Q2: %w\n\n", Q2),
% pop element
V = Q2.pop(Q3),
% display results
printf("Pop : Value: %w Queue: %w\n\n", V, Q3),
% test the queue
print("Test of the queue: "),
( Q3.empty() -> println("Queue empty"); println("Queue not empty") ),
nl,
% pop the elements
print("Pop the queue : "),
V1 = Q3.pop(Q4),
printf("Value %w Queue : %w%n%n", V1, Q4),
println("Pop empty queue:"),
catch(_V = Q4.pop(_Q5),Exception,println(Exception)),
nl,
 
println("\nEnd of tests.").</syntaxhighlight>
 
{{out}}
<pre>Test 1
 
Create queue []
 
Add numbers 1 and 2 :
Q2: [2,1]
 
Pop : Value: 1 Queue: [2]
 
Test of the queue: Queue not empty
 
Pop the queue : Value 2 Queue : []
 
Pop empty queue:
error(empty_queue,pop,Q = [])
 
End of tests.</pre>
 
===Always returning the queue===
Another approach is to always returns the queue which makes command chaining possible, e,g,
<pre> Q := Q.push2(1).push2(2),
Q := Q.pop2(V1).pop2(V2)
</pre>
 
<syntaxhighlight lang="picat">go2 =>
println("Test 2"),
queue_test2,
nl.
 
empty2() = [].
push2(Queue, Value) = Q2 =>
Q2 = [Value] ++ Queue.
pop2(Q,_) = _, Q==[] ; var(Q) =>
throw $error(empty_queue,pop,'Q'=Q).
pop2(Queue,V) = [Queue[I] : I in 1..Queue.len-1] =>
V = Queue.last().
 
queue_test2 =>
% create an empty queue
Q = empty2(),
printf("Create queue %w%n%n", Q),
% add numbers 1 and 2
println("Add numbers 1 and 2 : "),
Q := Q.push2(1).push2(2),
% display queue
printf("Q: %w\n\n", Q),
% pop element
Q := Q.pop2(V),
% display results
printf("Pop : Value: %w Queue: %w\n\n", V, Q),
% test the queue
print("Test of the queue: "),
( Q.empty() -> println("Queue empty"); println("Queue not empty") ),
nl,
% pop the elements
print("Pop the queue : "),
Q := Q.pop2(V2),
printf("Value %w Queue : %w%n%n", V2, Q),
println("Pop empty queue:"),
catch(_ = Q.pop2(_V),Exception,println(Exception)),
 
% command chaining
println("\nCommand chaining: "),
Q := Q.push2(3).push2(4),
Q := Q.pop2(V3).pop2(V4),
printf("V3: %w V4: %w\n", V3, V4),
nl,
println(q=Q).</syntaxhighlight>
 
{{out}}
<pre>Test 2
 
Create queue []
 
Add numbers 1 and 2 :
Q: [2,1]
 
Pop : Value: 1 Queue: [2]
 
Test of the queue: Queue not empty
 
Pop the queue : Value 2 Queue : []
 
Pop empty queue:
error(empty_queue,pop,Q = [])
 
Command chaining:
V3: 3 V4: 4
 
q = []</pre>
 
=={{header|PicoLisp}}==
The built-in function 'fifo' maintains a queue in a circular list, with direct
access to the first and the last cell
<langsyntaxhighlight PicoLisplang="picolisp">(off Queue) # Clear Queue
(fifo 'Queue 1) # Store number '1'
(fifo 'Queue 'abc) # an internal symbol 'abc'
(fifo 'Queue "abc") # a transient symbol "abc"
(fifo 'Queue '(a b c)) # and a list (a b c)
Queue # Show the queue</langsyntaxhighlight>
{{out}}
<pre>->((a b c) 1 abc "abc" .)</pre>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
/* To push a node onto the end of the queue. */
push: procedure (tail);
Line 3,242 ⟶ 5,134:
return (h = bind(:Node, null:) );
end empty;
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
% our queue is just [] and empty? is already defined.
/push {exch tadd}.
/pop {uncons exch}.
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}<br/>
PowerShell can natively use the .Net Queue class.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Q = New-Object System.Collections.Queue
Line 3,272 ⟶ 5,164:
{ $Q.Dequeue() }
catch [System.InvalidOperationException]
{ If ( $_.Exception.Message -eq 'Queue empty.' ) { 'Caught error' } }</langsyntaxhighlight>
{{out}}
<pre>1
Line 3,284 ⟶ 5,176:
Works with SWI-Prolog.
One can push any data in queue.
<langsyntaxhighlight Prologlang="prolog">empty(U-V) :-
unify_with_occurs_check(U, V).
 
Line 3,295 ⟶ 5,187:
 
append_dl(X-Y, Y-Z, X-Z).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
For FIFO function PureBasic normally uses linked lists.
Usage as described above could look like;
<langsyntaxhighlight PureBasiclang="purebasic">NewList MyStack()
 
Procedure Push(n)
Line 3,337 ⟶ 5,229:
Wend
;---- Now an extra Pop(), e.g. one to many ----
Debug Pop()</langsyntaxhighlight>
 
{{out}}
Line 3,353 ⟶ 5,245:
To encapsulate this behavior into a class and provide the task's specific API we can simply use:
 
<langsyntaxhighlight lang="python"> class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
Line 3,397 ⟶ 5,289:
f = FIFO(3,2,1)
for i in f:
print i,</langsyntaxhighlight>
 
This example does add to a couple of features which are easy in Python and allow this FIFO class to be used in ways that Python programmers might find more natural. Our ''__init__'' accepts and optional list of initial values, we add ''__len__'' and ''extend'' methods which simply wrap the corresponding list methods; we define a ''__call__'' method to show how one can make objects "callable" as functions, and we define ''__iter__'' and ''next()'' methods to facilitate using these FIFO objects with Python's prevalent iteration syntax (the ''for'' loop). The ''empty'' method could be implemented as simply an alias for ''__len__'' --- but we've chosen to have it more strictly conform to the task specification. Implementing the ''__len__'' method allows code using this object to test of emptiness using normal Python idioms for "truth" (any non-empty container is considered to be "true" and any empty container evaluates as "false").
Line 3,405 ⟶ 5,297:
That sort of wrapper looks like:
 
<langsyntaxhighlight lang="python">class FIFO: ## NOT a new-style class, must not derive from "object"
def __init__(self,*args):
self.contents = list(args)
Line 3,419 ⟶ 5,311:
if not self:
raise StopIteration
return self.pop()</langsyntaxhighlight>
 
As noted in the contents this must NOT be a new-style class, it must NOT but sub-classed from ''object'' nor any of its descendents. (A new-style implementation using __getattribute__ would be possible)
Line 3,427 ⟶ 5,319:
Python 2.4 and later includes a [http://docs.python.org/lib/deque-objects.html deque class], supporting thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. For other options see [http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436 Python Cookbook].
 
<langsyntaxhighlight lang="python">from collections import deque
fifo = deque()
fifo. appendleft(value) # push
value = fifo.pop()
not fifo # empty
fifo.pop() # raises IndexError when empty</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ [] ] is queue ( --> [ )
 
[ [] = ] is empty? ( [ --> b )
 
[ nested join ] is push ( [ x --> [ )
 
[ dup empty? if
[ $ "Queue unexpectedly empty."
fail ]
behead ] is pop ( [ --> [ x )</syntaxhighlight>
 
{{out}}
 
Testing in the Quackery shell.
 
<pre>/O> queue
... 1111 push
... 2222 push
... 3333 push
... pop echo cr
... pop echo cr
... pop echo cr
... dup empty? if [ say "queue is enpty" cr ]
... pop echo cr
...
1111
2222
3333
queue is enpty
 
Problem: Queue unexpectedly empty.
Quackery Stack: [ ]
Return stack: {[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 20} {pop 3}</pre>
 
=={{header|R}}==
===Simple functional implementation===
This simple implementation provides three functions that act on a variable in the global environment (user workspace) named ''l''. the push and pop functions display the new status of ''l'', but return NULL silently.
<langsyntaxhighlight Rlang="r">empty <- function() length(l) == 0
push <- function(x)
{
Line 3,484 ⟶ 5,412:
# list()
pop()
# Error in pop() : can't pop from an empty list</langsyntaxhighlight>
 
The problem with this is that the functions aren't related to the FIFO object (the list ''l''), and they require the list to exist in the global environment. (This second problem is possible to get round by passing ''l'' into the function and then returning it, but that is extra work.)
Line 3,490 ⟶ 5,418:
===Message passing===
 
<langsyntaxhighlight lang="r"># The usual Scheme way : build a function that takes commands as parameters (it's like message passing oriented programming)
queue <- function() {
v <- list()
Line 3,528 ⟶ 5,456:
# [1] 1
b("pop")
# [1] 3</langsyntaxhighlight>
 
===Object oriented implementation===
Line 3,534 ⟶ 5,462:
A better solution is to use the object oriented facility in the proto package. (R does have it's own native object oriented code, though the proto package is often nicer to use.)
 
<langsyntaxhighlight Rlang="r">library(proto)
 
fifo <- proto(expr = {
Line 3,563 ⟶ 5,491:
fifo$pop()
fifo$pop()
fifo$pop()</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 3,570 ⟶ 5,498:
Here's an explicit implementation:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 3,593 ⟶ 5,521:
(pop! Q) ; -> 'x
(list (pop! Q) (pop! Q) (pop! Q)) ; -> '(0 1 2)
</syntaxhighlight>
</lang>
 
And this is an implementation of a functional queue.
<langsyntaxhighlight lang="racket">
#lang racket
;; Invariants:
Line 3,629 ⟶ 5,557:
(push x q)))))
;; => 3
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
We could build a new container class to do FIFO pretty easily, but Arrays already do everything needed by a FIFO queue, so it is easier to just compose a Role on the existing Array class.
<syntaxhighlight lang="raku" line>role FIFO {
method enqueue ( *@values ) { # Add values to queue, returns the number of values added.
self.push: @values;
return @values.elems;
}
method dequeue ( ) { # Remove and return the first value from the queue.
# Return Nil if queue is empty.
return self.elems ?? self.shift !! Nil;
}
method is-empty ( ) { # Check to see if queue is empty. Returns Boolean value.
return self.elems == 0;
}
}
 
# Example usage:
 
my @queue does FIFO;
 
say @queue.is-empty; # -> Bool::True
for <A B C> -> $i { say @queue.enqueue: $i } # 1 \n 1 \n 1
say @queue.enqueue: Any; # -> 1
say @queue.enqueue: 7, 8; # -> 2
say @queue.is-empty; # -> Bool::False
say @queue.dequeue; # -> A
say @queue.elems; # -> 4
say @queue.dequeue; # -> B
say @queue.is-empty; # -> Bool::False
say @queue.enqueue('OHAI!'); # -> 1
say @queue.dequeue until @queue.is-empty; # -> C \n Any() \n [7 8] \n OHAI!
say @queue.is-empty; # -> Bool::True
say @queue.dequeue; # -></syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight REBOLlang="rebol">rebol [
Title: "FIFO"
URL: http://rosettacode.org/wiki/FIFO
Line 3,662 ⟶ 5,626:
while [not q/empty][print [" " q/pop]]
print rejoin ["Queue is " either q/empty [""]["not "] "empty."]
print ["Trying to pop an empty queue yields:" q/pop]</langsyntaxhighlight>
 
{{out}}
Line 3,677 ⟶ 5,641:
 
=={{header|REXX}}==
Support for &nbsp; '''LIFO''' &nbsp; <small> &amp; </small> &nbsp; '''FIFO''' &nbsp; queues is built into the [[REXX|Rexx]] language.
 
<br>The following are supported in REXX:
The following are supported in REXX:
* &nbsp; '''PUSH''' &nbsp; &nbsp; (lifo)
* &nbsp; '''QUEUE''' &nbsp; (fifo)
Line 3,690 ⟶ 5,655:
it has to do with the number of lines not yet read in an open (for read) file.
-- Gerard Schildberger. -->
 
<lang rexx>/*REXX program to demonstrate FIFO queue usage by some simple operations*/
<syntaxhighlight lang="rexx">/*REXX program to demonstrate FIFO queue usage by some simple operations*/
call viewQueue
a="Fred"
Line 3,709 ⟶ 5,675:
viewQueue: if queued()==0 then say 'Queue is empty'
else say 'There are' queued() 'elements in the queue'
return</langsyntaxhighlight>
'''output'''
<pre>
Line 3,723 ⟶ 5,689:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Queue/Definition
 
Line 3,743 ⟶ 5,709:
see "Error: queue is empty" + nl
ok
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,756 ⟶ 5,722:
Error: queue is empty
</pre>
 
=={{header|RPL}}==
It is rather easy to create queues in RPL, thanks to the list data structure. For mysterious reasons, it is very simple to add an item to a list, but quite complex to remove one: the size difference between <code>PUSH</code> and <code>POP</code> highlights it.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
'''QUEUE''' SIZE NOT ≫ ''''EMPTY'''' STO
'''QUEUE''' + ''''QUEUE'''' STO ≫ ''''PUSH'''' STO
IF '''QUEUE''' SIZE THEN
LAST { }
1 LAST 1 - FOR j
'''QUEUE''' j GET + NEXT
'''QUEUE''' ROT GET SWAP ''''QUEUE'''' STO
ELSE "ERR_Empty" END
≫ ''''POP'''' STO
|
'''EMPTY''' ''( -- )''
Test the global variable QUEUE
'''PUSH''' ''( item -- )''
Add the item at the beginning of the list
'''POP''' ''( -- item )''
Initialize stack
Copy all items except the last
in a new list
Get last item, update queue with new list
Handles the case of an empty queue
|}
{{in}}
<pre>
{ } 'QUEUE' STO
EMPTY
"The" PUSH
7 PUSH
{ Wonders } PUSH
QUEUE
EMPTY
POP
</pre>
{{out}}
<pre>
4: 1
3: { 'Wonders' 7 "The" }
2: 0
1: "The"
</pre>
===Shorter POP version===
This approach might be suitable for small queue sizes only, since it uses the stack to temporarily store the whole queue.
≪ IF '''QUEUE''' SIZE THEN
'''QUEUE''' LIST→ ROLLD LAST 1 - →LIST ''''QUEUE'''' STO
ELSE "ERR_Empty" END
≫ ''''POP'''' STO
 
=={{header|Ruby}}==
The core class ''Array'' already implements all queue operations, so this class ''FIFO'' delegates everything to methods of ''Array''.
 
<langsyntaxhighlight lang="ruby">require 'forwardable'
 
# A FIFO queue contains elements in first-in, first-out order.
Line 3,816 ⟶ 5,845:
end
alias inspect to_s
end</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ruby">f = FIFO.new
f.empty? # => true
f.pop # => nil
Line 3,833 ⟶ 5,862:
g.pop(2) # => [:a, :b]
g.pop(2) # => [:c]
g.pop(2) # => []</langsyntaxhighlight>
 
 
=={{header|Rust}}==
===Using the standard library===
The standard library has a double-ended queue implementation (<code>VecDeque<T></code>) which will work here.
<langsyntaxhighlight lang="rust">use std::collections::VecDeque;
fn main() {
let mut stack = VecDeque::new();
Line 3,851 ⟶ 5,879:
assert_eq!(Some("Element3"), stack.pop_front());
assert_eq!(None, stack.pop_front());
}</langsyntaxhighlight>
===A simple implementation===
This shows the implementation of a singly-linked queue with <code>dequeue</code> and <code>enqueue</code>. There are two <code>peek</code> implementations, one returns an immutable reference, the other returns a mutable one. This implementation also shows iteration over the Queue by value (consumes queue), immutable reference, and mutable reference.
<langsyntaxhighlight lang="rust">use std::ptr;
 
pub struct Queue<T> {
Line 3,977 ⟶ 6,005:
})
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">class Queue[T] {
private[this] class Node[T](val value:T) {
var next:Option[Node[T]]=None
Line 4,013 ⟶ 6,041:
override def toString()=iterator.mkString("Queue(", ", ", ")")
}</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="scala">val q=new Queue[Int]()
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
Line 4,025 ⟶ 6,053:
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)</langsyntaxhighlight>
{{out}}
<pre>isEmpty = true
Line 4,040 ⟶ 6,068:
in the vector to hold tail pointer to avoid the append call.
 
<langsyntaxhighlight lang="scheme">(define (make-queue)
(make-vector 1 '()))
 
Line 4,055 ⟶ 6,083:
(vector-set! queue 0 (cdr (vector-ref queue 0)))
ret)))
</syntaxhighlight>
</lang>
 
=== Message passing ===
<langsyntaxhighlight lang="scheme">(define (make-queue)
(let ((q (cons '() '())))
(lambda (cmd . arg)
Line 4,082 ⟶ 6,110:
; 6
(q 'get)
; empty</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
A queue in SenseTalk is implemented using push and pull operations on a list.
<syntaxhighlight lang="sensetalk">
set myFoods to be an empty list
 
push "grapes" into myFoods
push "orange" into myFoods
push "apricot" into myFoods
 
put "The foods in my queue are: " & myFoods
 
pull from myFoods into firstThingToEat
 
put "The first thing to eat is: " & firstThingToEat
 
if myFoods is empty then
put "The foods list is empty!"
else
put "The remaining foods are: " & myFoods
end if
</syntaxhighlight>
Output:
<syntaxhighlight lang="sensetalk">
The foods in my queue are: (grapes,orange,apricot)
The first thing to eat is: grapes
The remaining foods are: (orange,apricot)
</syntaxhighlight>
 
=={{header|Sidef}}==
Implemented as a class:
<langsyntaxhighlight lang="ruby">class FIFO(*array) {
method pop {
array.is_empty && die "underflow";
Line 4,098 ⟶ 6,154:
array.len == 0;
}
}</langsyntaxhighlight>
 
=={{header|Slate}}==
Toy code based on Slate's Queue standard library (which is optimized for FIFO access):
<langsyntaxhighlight lang="slate">collections define: #Queue &parents: {ExtensibleArray}.
 
q@(Queue traits) isEmpty [resend].
Line 4,108 ⟶ 6,164:
q@(Queue traits) pop [q removeFirst].
q@(Queue traits) pushAll: c [q addAllLast: c].
q@(Queue traits) pop: n [q removeFirst: n].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
Line 4,115 ⟶ 6,171:
An OrderedCollection can be easily used as a FIFO queue.
 
<langsyntaxhighlight lang="smalltalk">OrderedCollection extend [
push: obj [ ^(self add: obj) ]
pop [
Line 4,134 ⟶ 6,190:
f pop printNl.
f isEmpty printNl.
f pop. "queue empty error"</langsyntaxhighlight>
 
=={{header|Standard ML}}==
Here is the signature for a basic queue:
<syntaxhighlight lang="standard ml">
<lang Standard ML>
signature QUEUE =
sig
Line 4,151 ⟶ 6,207:
val empty: 'a queue -> bool
end;
</syntaxhighlight>
</lang>
A very basic implementation of this signature backed by a list is as follows:
<syntaxhighlight lang="standard ml">
<lang Standard ML>
structure Queue:> QUEUE =
struct
Line 4,170 ⟶ 6,226:
| empty _ = false
end;
</syntaxhighlight>
</lang>
 
 
=={{header|Stata}}==
See [[Singly-linked list/Element definition#Stata]].
 
=={{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 4,207 ⟶ 6,263:
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar</langsyntaxhighlight>
 
{{tcllib|struct::queue}}
<langsyntaxhighlight lang="tcl">package require struct::queue
struct::queue Q
Q size ;# ==> 0
Line 4,219 ⟶ 6,275:
Q peek ;# ==> b
Q pop 4 ;# ==> b c d e
Q size ;# ==> 0</langsyntaxhighlight>
 
=={{header|UnixPipes}}==
Uses moreutils
<lang bash>init() {echo > fifo}
push() {echo $1 >> fifo }
pop() {head -1 fifo ; (cat fifo | tail -n +2)|sponge fifo}
empty() {cat fifo | wc -l}</lang>
Usage:
<lang bash>push me; push you; push us; push them
|pop;pop;pop;pop
me
you
us
them</lang>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<langsyntaxhighlight lang="bash">queue_push() {
typeset -n q=$1
shift
Line 4,261 ⟶ 6,303:
typeset -n q=$1
print "${q[0]}"
}</langsyntaxhighlight>
 
Usage:
<langsyntaxhighlight lang="bash"># any valid variable name can be used as a queue without initialization
 
queue_empty foo && echo foo is empty || echo foo is not empty
Line 4,277 ⟶ 6,319:
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo</langsyntaxhighlight>
 
{{out}}
Line 4,287 ⟶ 6,329:
peek:
queue foo is empty</pre>
 
=={{header|UnixPipes}}==
Uses moreutils
<syntaxhighlight lang="bash">init() {echo > fifo}
push() {echo $1 >> fifo }
pop() {head -1 fifo ; (cat fifo | tail -n +2)|sponge fifo}
empty() {cat fifo | wc -l}</syntaxhighlight>
Usage:
<syntaxhighlight lang="bash">push me; push you; push us; push them
|pop;pop;pop;pop
me
you
us
them</syntaxhighlight>
 
=={{header|V}}==
V doesn't have mutable data. Below is an function interface for a fifo.
 
<langsyntaxhighlight lang="v">[fifo_create []].
[fifo_push swap cons].
[fifo_pop [[*rest a] : [*rest] a] view].
[fifo_empty? dup empty?].</langsyntaxhighlight>
 
Using it
<langsyntaxhighlight lang="v">|fifo_create 3 fifo_push 4 fifo_push 5 fifo_push ??
=[5 4 3]
|fifo_empty? puts
Line 4,304 ⟶ 6,360:
=3 4 5
|fifo_empty? puts
=true</langsyntaxhighlight>
 
=={{header|VBA}}==
<syntaxhighlight lang="vb">Public queue As New Collection
 
Private Sub push(what As Variant)
queue.Add what
End Sub
 
Private Function pop() As Variant
If queue.Count > 0 Then
what = queue(1)
queue.Remove 1
Else
what = CVErr(461)
End If
pop = what
End Function
 
Private Function empty_()
empty_ = queue.Count = 0
End Function</syntaxhighlight>
 
=={{header|VBScript}}==
Using an ArrayList.
<syntaxhighlight lang="vb">' Queue Definition - VBScript
Option Explicit
Dim queue, i, x
Set queue = CreateObject("System.Collections.ArrayList")
If Not empty_(queue) Then Wscript.Echo queue.Count
push queue, "Banana"
push queue, "Apple"
push queue, "Pear"
push queue, "Strawberry"
Wscript.Echo "Count=" & queue.Count
Wscript.Echo pull(queue) & " - Count=" & queue.Count '
Wscript.Echo "Head=" & queue.Item(0)
Wscript.Echo "Tail=" & queue.Item(queue.Count-1)
Wscript.Echo queue.IndexOf("Pear", 0)
For i=1 To queue.Count
Wscript.Echo join(queue.ToArray(), ", ")
x = pull(queue)
Next 'i
 
Sub push(q, what)
q.Add what
End Sub 'push
Function pull(q)
Dim what
If q.Count > 0 Then
what = q(0)
q.RemoveAt 0
Else
what = ""
End If
pull = what
End Function 'pull
Function empty_(q)
empty_ = q.Count = 0
End Function 'empty_
</syntaxhighlight>
{{out}}
<pre>
Count=4
Banana - Count=3
Head=Apple
Tail=Strawberry
1
Apple, Pear, Strawberry
Pear, Strawberry
Strawberry
</pre>
 
=={{header|V (Vlang)}}==
Updated to V (Vlang) version 0.2.2
<syntaxhighlight lang="v (vlang)">const max_tail = 256
struct Queue<T> {
mut:
data []T
tail int
head int
}
fn (mut queue Queue<T>) push(value T) {
if queue.tail >= max_tail || queue.tail < queue.head {
return
}
println('push: $value')
queue.data << value
queue.tail++
}
fn (mut queue Queue<T>) pop() !T {
if queue.tail > 0 && queue.head < queue.tail {
result := queue.data[queue.head]
queue.head++
println('Dequeue: top of Queue was $result')
return result
}
return error('Queue Underflow!!')
}
fn (queue Queue<T>) peek() !T {
if queue.tail > 0 && queue.head < queue.tail {
result := queue.data[queue.head]
println('Peek: top of Queue is $result')
return result
}
return error('Out of Bounds...')
}
fn (queue Queue<T>) empty() bool {
return queue.tail == 0
}
fn main() {
mut queue := Queue<f64>{}
println('Queue is empty? ' + if queue.empty() { 'Yes' } else { 'No' })
queue.push(5.0)
queue.push(4.2)
println('Queue is empty? ' + if queue.empty() { 'Yes' } else { 'No' })
queue.peek() or { return }
queue.pop() or { return }
queue.pop() or { return }
queue.push(1.2)
}</syntaxhighlight>
{{out}}
<pre>Queue is empty? Yes
Enqueue: 5.00
Enqueue: 4.20
Queue is empty? No
Peek: top of Queue is 5.00
Dequeue: top of Queue was 5.00
Dequeue: top of Queue was 4.20
Enqueue: 1.20
</pre>
 
=={{header|Wart}}==
Wart defines queues as lists with a pointer to the last element saved for constant-time enqueuing:
<langsyntaxhighlight lang="python">def (queue seq)
(tag queue (list seq lastcons.seq len.seq))
 
Line 4,327 ⟶ 6,521:
 
def (len q) :case (isa queue q)
rep.q.2</langsyntaxhighlight>
 
<code>empty?</code> relies on <code>len</code> by default, so there's no need to separately override it.
 
=={{header|Wren}}==
{{libheader|Wren-queue}}
The above module contains a suitable Queue class.
<syntaxhighlight lang="wren">import "./queue" for Queue
 
var q = Queue.new()
var item = q.pop()
if (item == null) {
System.print("ERROR: attempted to pop from an empty queue")
} else {
System.print("'%(item)' was popped")
}</syntaxhighlight>
 
{{out}}
<pre>
ERROR: attempted to pop from an empty queue
</pre>
 
=={{header|XLISP}}==
A queue is similar to a stack, except that values are pushed onto and popped from different "ends" of it (whereas in a stack it is the same end for both operations). This implementation is based on the XLISP implementation of a stack, therefore, but with a <tt>push</tt> method that appends a new value to the end rather than sticking it onto the front. Attempting to pop from an empty queue will return the empty list, equivalent to Boolean "false".
<langsyntaxhighlight lang="lisp">(define-class queue
(instance-variables vals))
Line 4,349 ⟶ 6,561:
(define-method (queue 'emptyp)
(null vals))</langsyntaxhighlight>
A sample REPL session:
<langsyntaxhighlight lang="lisp">[1] (define my-queue (queue 'new))
 
MY-QUEUE
Line 4,374 ⟶ 6,586:
[8] (my-queue 'pop)
 
()</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
def Size=8;
int Fifo(Size);
Line 4,424 ⟶ 6,636:
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
]</langsyntaxhighlight>
 
Output:
Line 4,441 ⟶ 6,653:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">class Queue{
var [const] q=List();
fcn push { q.append(vm.pasteArgs()) }
fcn pop { q.pop(0) }
fcn empty { q.len()==0 }
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">q:=Queue();
q.push(1,2,3);
q.pop(); //-->1
q.empty(); //-->False
q.pop();q.pop();q.pop() //-->IndexError thrown</langsyntaxhighlight>
 
 
{{omit from|PL/0}}
2,044

edits