Queue/Usage: Difference between revisions

m
 
(39 intermediate revisions by 24 users not shown)
Line 16:
{{Template:See also lists}}
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">Deque[String] my_queue
 
my_queue.append(‘foo’)
my_queue.append(‘bar’)
my_queue.append(‘baz’)
 
print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())</syntaxhighlight>
 
{{out}}
<pre>
foo
bar
baz
</pre>
=={{header|6502 Assembly}}==
Implementing a queue is very similar to a software stack, except the <code>POP</code> command is a litte more involved. The basic principles are the same: Before the queue can be used, a "queue pointer" must first be loaded into X, which points to the first empty slot in the queue. The queue grows down in memory as new elements join the queue. This software queue uses the zero page as the storage area.
 
 
<syntaxhighlight lang="6502asm">
queuePointerStart equ #$FD
queuePointerMinus1 equ #$FC ;make this equal whatever "queuePointerStart" is, minus 1.
pushQueue:
STA 0,x
DEX
RTS
 
popQueue:
STX temp
LDX #queuePointerStart
LDA 0,x ;get the item that's first in line
PHA
LDX #queuePointerMinus1
loop_popQueue:
LDA 0,X
STA 1,X
DEX
CPX temp
BNE loop_popQueue
LDX temp
INX
PLA ;return the item that just left the queue
RTS
 
isQueueEmpty:
LDA #1
CPX #queuePointerStart
BEQ yes ;return 1
 
SEC
SBC #1 ;return 0
 
yes:
RTS</syntaxhighlight>
 
===PUSH===
This example uses Easy6502 to test the various modes. The first test pushes three values into the queue. For all examples, the subroutines above are defined below the <code>BRK</code>.
 
<syntaxhighlight lang="6502asm">define temp $00
define queueEmpty $FD
define queueAlmostEmpty $FC
 
LDX #queueEmpty ;set up software queue
 
LDA #$40
jsr pushQueue
 
LDA #$80
jsr pushQueue
 
LDA #$C0
jsr pushQueue
 
brk</syntaxhighlight>
 
Output of Example 1:
<pre>
Queue Pointer = $FA
 
Hexdump of $00fa: 00 c0 80 40
Address of each: (FA FB FC FD)
</pre>
===POP===
<syntaxhighlight lang="6502asm">define temp $00
define queueEmpty $FD
define queueAlmostEmpty $FC
 
LDX #queueEmpty ;set up software queue
 
LDA #$40
jsr pushQueue
 
LDA #$80
jsr pushQueue
 
LDA #$C0
jsr pushQueue
 
jsr popQueue
 
brk</syntaxhighlight>
 
Output of Example 2:
<pre>
Queue Pointer = $FB
Hexdump of $00FB: c0 c0 80
Address of each: (FB FC FD)
 
Note that c0 still exists in FB, but its slot is "empty" so it will get overwritten in the 3rd example.
</pre>
 
===PUSH,POP,PUSH===
This example shows that once an item leaves the queue, the "ghost" of the last item in line gets overwritten with the next item to join.
<syntaxhighlight lang="6502asm">define temp $00
define queueEmpty $FD
define queueAlmostEmpty $FC
 
 
LDX #queueEmpty ;set up software queue
 
LDA #$40
jsr pushQueue
 
LDA #$80
jsr pushQueue
 
LDA #$C0
jsr pushQueue
 
jsr popQueue
 
lda #$ff
jsr pushQueue
 
brk</syntaxhighlight>
 
Output of Example 3:
<pre>
Queue Pointer = $FA
Hexdump of $00FA: 00 ff c0 80
Address of each: (FA FB FC FD)
</pre>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
10 q:new \ create a new queue 10 deep
123 q:push
Line 26 ⟶ 172:
q:pop . cr \ displays 341
q:len . cr \ displays 0
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
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="4"
TYPE QueueNode=[PTR data,nxt]
 
QueueNode POINTER queueFront,queueRear
 
BYTE FUNC IsEmpty()
IF queueFront=0 THEN
RETURN (1)
FI
RETURN (0)
 
PROC Push(CHAR ARRAY 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
 
PTR FUNC Pop()
QueueNode POINTER node
CHAR ARRAY 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(CHAR ARRAY v)
PrintF("Push: %S%E",v)
Push(v)
RETURN
 
PROC TestPop()
CHAR ARRAY v
 
Print("Pop: ")
v=Pop()
PrintE(v)
RETURN
 
PROC Main()
AllocInit(0)
queueFront=0
queueRear=0
 
Put(125) PutE() ;clear screen
 
TestIsEmpty()
TestPush("foo")
TestIsEmpty()
TestPush("bar")
TestPop()
TestIsEmpty()
TestPush("baz")
TestPop()
TestIsEmpty()
TestPop()
TestIsEmpty()
TestPop()
RETURN</syntaxhighlight>
{{out}}
Error at the end of the program is intentional.
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Queue_Usage.png Screenshot from Atari 8-bit computer]
<pre>
Queue is empty
Push: foo
Queue is not empty
Push: bar
Pop: foo
Queue is not empty
Push: baz
Pop: bar
Queue is not empty
Pop: baz
Queue is empty
Pop: Error: queue is empty!
 
RETURN
Error: 128
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with FIFO;
with Ada.Text_Io; use Ada.Text_Io;
Line 48 ⟶ 305:
Pop (Queue, Value);
Put_Line ("Is_Empty " & Boolean'Image (Is_Empty (Queue)));
end Queue_Test;</langsyntaxhighlight>
Sample output:
<pre>Is_Empty TRUE</pre>
Line 59 ⟶ 316:
'''File: prelude/link.a68''' c.f. [[Queue/Definition#ALGOL 68|Queue/Definition]]<br>
'''File: prelude/queue_base.a68''' c.f. [[Queue/Definition#ALGOL 68|Queue/Definition]]<br>
'''File: test/data_stigler_diet.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
MODE DIETITEM = STRUCT(
STRING food, annual quantity, units, REAL cost
Line 73 ⟶ 330:
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
)</langsyntaxhighlight>'''File: test/queue.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 92 ⟶ 349:
# OR example queue ISNT obj queue empty #
printf((diet item fmt, obj queue get(example queue), $l$))
OD</langsyntaxhighlight>'''Output:'''
<pre>
Get remaining values from queue:
Line 103 ⟶ 360:
</pre>
'''See also:''' [[Stack#ALGOL_68|Stack]]
 
=={{header|App Inventor}}==
This Rosetta Code Task requires that the queue operations of push (enqueue), pop (dequeue) and empty be demonstrated with App Inventor.<br>
This is easy to do as those operations are basically available in a slightly different form as list operations.<br>
In addition for this example, I added a top function to view the first item in the queue.<br>
<br>
The solution is a complete (although greatly simplified) hamburger restaurant where the customers and orders are the queues.<br>
 
Customers enter the restaurant at random intervals between 2 and 10 seconds (Customers Clock Timer)<br>
Each customer will request a random item from the menu.<br>
If the item is not available, the customer leaves.<br>
If that item is available (there are only 30 of each item) then the order is placed and payment is accepted (push|enqueue Customer, push|enqueue Order).<br>
Once an order is placed, the customer must wait for the meal to be prepared -- each menu item takes a different number of seconds to prepare (Orders Clock Timer.)<br>
Once the item is prepared, their customer name and the ordered item are removed from the queues (pop|dequeue Customer, pop|dequeue Order).<br>
If there are no pending orders, (empty Orders queue) the cook just waits for one to be placed (the orders clock continues to run to poll for new orders by testing if the Orders queue is not empty.)<br>
Eventually, all items will have been sold, and the store manager will empty the cash register and fly to Tahiti with the waitress.<br>
The eager -- but destined to be frustrated customers -- will continue to request their random items, forever. :)<br>
[https://lh6.googleusercontent.com/-dTvs9totvDE/Uu3ZiFeE90I/AAAAAAAAJ-w/lJBVHOd-p0g/s1600/Untitled.png CLICK HERE TO VIEW THE CODE BLOCKS AND ANDROID APP SCREEN]
---
END
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript ">on push(StackRef, value)
set StackRef's contents to {value} & StackRef's contents
return StackRef
Line 133 ⟶ 410:
pop(a reference to theStack)
log result
end repeat</langsyntaxhighlight>Output (in Script Editor Event Log):<pre> (*1*)
(*2, 1*)
(*3, 2, 1*)
Line 145 ⟶ 422:
</pre>
 
=={{header|App InventorArturo}}==
This Rosetta Code Task requires that the queue operations of push (enqueue), pop (dequeue) and empty be demonstrated with App Inventor.<br>
This is easy to do as those operations are basically available in a slightly different form as list operations.<br>
In addition for this example, I added a top function to view the first item in the queue.<br>
<br>
The solution is a complete (although greatly simplified) hamburger restaurant where the customers and orders are the queues.<br>
 
<syntaxhighlight lang="arturo">define :queue [][
Customers enter the restaurant at random intervals between 2 and 10 seconds (Customers Clock Timer)<br>
init: [
Each customer will request a random item from the menu.<br>
this\items: []
If the item is not available, the customer leaves.<br>
]
If that item is available (there are only 30 of each item) then the order is placed and payment is accepted (push|enqueue Customer, push|enqueue Order).<br>
]
Once an order is placed, the customer must wait for the meal to be prepared -- each menu item takes a different number of seconds to prepare (Orders Clock Timer.)<br>
 
Once the item is prepared, their customer name and the ordered item are removed from the queues (pop|dequeue Customer, pop|dequeue Order).<br>
empty?: function [this :queue][
If there are no pending orders, (empty Orders queue) the cook just waits for one to be placed (the orders clock continues to run to poll for new orders by testing if the Orders queue is not empty.)<br>
zero? this\items
Eventually, all items will have been sold, and the store manager will empty the cash register and fly to Tahiti with the waitress.<br>
]
The eager -- but destined to be frustrated customers -- will continue to request their random items, forever. :)<br>
 
[https://lh6.googleusercontent.com/-dTvs9totvDE/Uu3ZiFeE90I/AAAAAAAAJ-w/lJBVHOd-p0g/s1600/Untitled.png CLICK HERE TO VIEW THE CODE BLOCKS AND ANDROID APP SCREEN]
push: function [this :queue, item][
---
this\items: this\items ++ item
END
]
 
pop: function [this :queue][
ensure -> not? empty? this
result: this\items\0
this\items: remove.index this\items 0
return result
]
 
Q: to :queue []
 
push Q 1
push Q 2
push Q 3
 
print ["queue is empty?" empty? Q]
 
print ["popping:" pop Q]
print ["popping:" pop Q]
print ["popping:" pop Q]
 
print ["queue is empty?" empty? Q]</syntaxhighlight>
 
{{out}}
 
<pre>queue is empty? false
popping: 1
popping: 2
popping: 3
queue is empty? true</pre>
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">let my_queue = Queue()
 
my_queue.push!('foo')
Line 174 ⟶ 477:
print my_queue.pop!() # 'foo'
print my_queue.pop!() # 'bar'
print my_queue.pop!() # 'baz'</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST
 
MsgBox % "Len = " len("qu") ; Number of entries
Line 207 ⟶ 510:
StringReplace %queue%, %queue%, |, |, UseErrorLevel
Return %queue% = "" ? 0 : ErrorLevel+1
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">function deque(arr) {
arr["start"] = 0
arr["end"] = 0
}
 
function dequelen(arr) {
return arr["end"] - arr["start"]
}
 
function empty(arr) {
return dequelen(arr) == 0
}
 
function push(arr, elem) {
arr[++arr["end"]] = elem
}
 
function pop(arr) {
if (empty(arr)) {
return
}
return arr[arr["end"]--]
}
 
function unshift(arr, elem) {
arr[arr["start"]--] = elem
}
 
function shift(arr) {
if (empty(arr)) {
return
}
return arr[++arr["start"]]
}
 
function printdeque(arr, i, sep) {
printf("[")
for (i = arr["start"] + 1; i <= arr["end"]; i++) {
printf("%s%s", sep, arr[i])
sep = ", "
}
printf("]\n")
}
 
BEGIN {
deque(q)
for (i = 1; i <= 10; i++) {
push(q, i)
}
printdeque(q)
for (i = 1; i <= 10; i++) {
print shift(q)
}
printdeque(q)
}</syntaxhighlight>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> FIFOSIZE = 1000
FOR n = 3 TO 5
Line 241 ⟶ 602:
= (rptr% = wptr%)
ENDCASE
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 260 ⟶ 621:
 
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 297 ⟶ 658:
| out$"Attempt to dequeue failed"
)
;</langsyntaxhighlight>
Output:
<pre>1
Line 309 ⟶ 670:
=={{header|C}}==
See [[FIFO]] for the needed code.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 339 ⟶ 700:
 
exit(0);
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
In C# we can use the Queue<T> class in the .NET 2.0 framework.
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
namespace RosettaCode
{
class Program
{
static void Main()
{
// Create a queue and "push" items into it
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(3);
queue.Enqueue(5);
 
// "Pop" items from the queue in FIFO order
Console.WriteLine(queue.Dequeue()); // 1
Console.WriteLine(queue.Dequeue()); // 3
Console.WriteLine(queue.Dequeue()); // 5
 
// To tell if the queue is empty, we check the count
bool empty = queue.Count == 0;
Console.WriteLine(empty); // "True"
 
// If we try to pop from an empty queue, an exception
// is thrown.
try
{
queue.Dequeue();
}
catch (InvalidOperationException exception)
{
Console.WriteLine(exception.Message); // "Queue empty."
}
}
}
}</syntaxhighlight>
 
=={{header|C++}}==
Note that with C++'s standard queue, accessing the first element of the queue and removing it are two separate operations, <tt>front()</tt> and <tt>pop()</tt>.
<langsyntaxhighlight lang="cpp">#include <queue>
#include <cassert> // for run time assertions
 
Line 388 ⟶ 789:
q.pop();
assert( q.empty() );
}</langsyntaxhighlight>
 
Note that the container used to store the queue elements can be specified explicitly; to use a linked linst instead of a deque (the latter is the default), just replace the definition of <tt>q</tt> to
<langsyntaxhighlight lang="cpp"> std::queue<int, std::list<int> ></langsyntaxhighlight>
 
(and add <tt>#include <list></tt>, of course). Also note that the containers can be used directly; in that case <tt>push</tt> and <tt>pop</tt> have to be replaced by <tt>push_back</tt> and <tt>pop_front</tt>.
 
=={{header|C sharp}}==
In C# we can use the Queue<T> class in the .NET 2.0 framework.
<lang csharp>using System;
using System.Collections.Generic;
 
namespace RosettaCode
{
class Program
{
static void Main()
{
// Create a queue and "push" items into it
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(3);
queue.Enqueue(5);
 
// "Pop" items from the queue in FIFO order
Console.WriteLine(queue.Dequeue()); // 1
Console.WriteLine(queue.Dequeue()); // 3
Console.WriteLine(queue.Dequeue()); // 5
 
// To tell if the queue is empty, we check the count
bool empty = queue.Count == 0;
Console.WriteLine(empty); // "True"
 
// If we try to pop from an empty queue, an exception
// is thrown.
try
{
queue.Dequeue();
}
catch (InvalidOperationException exception)
{
Console.WriteLine(exception.Message); // "Queue empty."
}
}
}
}</lang>
 
=={{header|Clojure}}==
Using the implementation from [[FIFO]]:
<langsyntaxhighlight lang="lisp">(def q (make-queue))
 
(enqueue q 1)
Line 447 ⟶ 808:
(dequeue q) ; 3
 
(queue-empty? q) ; true</langsyntaxhighlight>
Or use a java implementation:
<langsyntaxhighlight lang="lisp">(def q (java.util.LinkedList.))
 
(.add q 1)
Line 459 ⟶ 820:
(.remove q) ; 3
 
(.isEmpty q) ; true</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
# We build a Queue on top of an ordinary JS array, which supports push
# and shift. For simple queues, it might make sense to just use arrays
Line 495 ⟶ 856:
catch e
console.log "#{e}"
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="text">
> coffee queue.coffee
1
100000
Error: queue is empty
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Using the implementation from [[FIFO]].
 
<langsyntaxhighlight lang="lisp">(let ((queue (make-queue)))
(enqueue 38 queue)
(assert (not (queue-empty-p queue)))
Line 513 ⟶ 874:
(assert (eql 38 (dequeue queue)))
(assert (eql 23 (dequeue queue)))
(assert (queue-empty-p queue)))</langsyntaxhighlight>
 
=={{header|Component Pascal}}==
BlackBox Component Builder
<langsyntaxhighlight lang="oberon2">
MODULE UseQueue;
IMPORT StdLog,Queue,Boxes;
Queue,
 
Boxes,
StdLog;
PROCEDURE Do*;
VAR
q: Queue.QueueInstance;
ob: Boxes.ObjectBox;
BEGIN
q := Queue.NewQueueNew(610);
q.Push(Boxes.NewInteger(1));
q.Push(Boxes.NewInteger(2));
q.Push(Boxes.NewInteger(3));
ob := q.Pop();
ob := q.Pop();
q.Push(Boxes.NewInteger(4));
ob := q.Pop();
ob := q.Pop();
StdLog.String("Is empty:> ");StdLog.Bool(q.IsEmpty());StdLog.Ln
q.Push(Boxes.NewInteger(5));
o := q.Pop();
StdLog.String("Is empty: ");StdLog.Bool(q.IsEmpty());StdLog.Ln
END Do;
END UseQueue.
</syntaxhighlight>
</lang>
Execute: ^Q UseQueue.Do<br/>
Output:
Line 546 ⟶ 908:
Is empty: $TRUE
</pre>
 
=={{header|Cowgol}}==
 
This code uses the queue code at [[Queue/Definition]], which should be put
in a file named <code>queue.coh</code>.
 
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
typedef QueueData is uint8; # the queue will contain bytes
include "queue.coh"; # from the Queue/Definition task
 
var queue := MakeQueue();
 
# enqueue bytes 0 to 20
print("Enqueueing: ");
var n: uint8 := 0;
while n < 20 loop
print_i8(n);
print_char(' ');
Enqueue(queue, n);
n := n + 1;
end loop;
print_nl();
 
# dequeue and print everything in the queue
print("Dequeueing: ");
while QueueEmpty(queue) == 0 loop
print_i8(Dequeue(queue));
print_char(' ');
end loop;
print_nl();
 
# free the queue
FreeQueue(queue);</syntaxhighlight>
 
{{out}}
 
<pre>Enqueueing: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Dequeueing: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">class LinkedQueue(T) {
private static struct Node {
T data;
Line 590 ⟶ 992:
assert(q.pop() == 30);
assert(q.empty());
}</langsyntaxhighlight>
 
===Faster Version===
This versions creates a circular queue able to grow. Define "queue_usage2_main" to run the main and its tests.
<langsyntaxhighlight lang="d">module queue_usage2;
 
import std.traits: hasIndirections;
Line 668 ⟶ 1,070:
}
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Generics were added in Delphi2009.
 
<langsyntaxhighlight Delphilang="delphi">program QueueUsage;
 
{$APPTYPE CONSOLE}
Line 697 ⟶ 1,099:
lStringQueue.Free;
end
end.</langsyntaxhighlight>
 
Output:
Line 704 ⟶ 1,106:
Third
Queue is empty.</pre>
 
=={{header|Déjà Vu}}==
This uses the definition from [[Queue/Definition#Déjà Vu]]
<langsyntaxhighlight lang="dejavu">local :Q queue
!. empty Q
enqueue Q "HELLO"
Line 716 ⟶ 1,119:
!. dequeue Q
!. empty Q
!. dequeue Q</langsyntaxhighlight>
{{out}}
<pre>true
Line 728 ⟶ 1,131:
queue.deja:28
queue.deja:10 in dequeue</pre>
 
=={{header|Diego}}==
Diego has a <code>queue</code> object and posit:
<syntaxhighlight lang="diego">set_ns(rosettacode)_me();
 
add_queue({int},q)_values(1..4); // 1,2,3,4 (1 is first/bottom, 4 is last/top)
with_queue(q)_pop(); // 2,3,4
with_queue(q)_dequeue(); // 3,4
with_queue(q)_enqueue(5); // 3,4,5
with_queue(q)_push()_v(6,7); // 3,4,5,6,7
 
add_var({int},b)_value(8);
with_queue(q)_push[b]; // 3,4,5,6,7,8
 
with_queue(q)_pluck()_at(2); // callee will return `with_queue(q)_err(pluck invalid with queue);`
 
me_msg()_queue(q)_top(); // "8"
me_msg()_queue(q)_last(); // "8"
me_msg()_queue(q)_peek(); // "8"
 
me_msg()_queue(q)_bottom(); // "3"
me_msg()_queue(q)_first(); // "3"
me_msg()_queue(q)_peer(); // "3"
 
me_msg()_queue(q)_isempty(); // "false"
with_queue(q)_empty();
with_queue(q)_msg()_isempty()_me(); // "true" (alternative syntax)
 
with_queue()_pop(); // callee will return `with_queue(q)_err(pop invalid with empty queue);`
 
me_msg()_queue(q)_history()_all(); // returns the entire history of queue 'q' since its creation
 
reset_namespace[];</syntaxhighlight>
<code>queue</code> is a derivative of <code>array</code>, so arrays can also be used as queues.
 
=={{header|E}}==
Using the implementation from [[FIFO]].
 
<langsyntaxhighlight lang="e">def [reader, writer] := makeQueue()
require(escape empty { reader.dequeue(empty); false } catch _ { true })
writer.enqueue(1)
Line 740 ⟶ 1,178:
require(reader.dequeue(throw) == 2)
require(reader.dequeue(throw) == 3)
require(escape empty { reader.dequeue(empty); false } catch _ { true })</langsyntaxhighlight>
 
E also has queues in the standard library such as <code>&lt;import:org.erights.e.examples.concurrency.makeQueue></code>, but they are designed for concurrency purposes and do not report emptiness but rather return a promise for the next element.
 
=={{header|EasyLang}}==
Uses the queue-definition given at [[Queue/Definition#EasyLang]]
<syntaxhighlight>
#
# queue definition
#
##
qu_enq 2
qu_enq 5
qu_enq 7
while qu_empty = 0
print qu_deq
.
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 36.4x :
<langsyntaxhighlight lang="elena">import system'collections.;
import extensions.;
public program()
{
[
console.
// Create a queue and "push" items into it
var queue := Queue new. Queue();
queue .push:(1.);
queue .push:(3.);
queue .push:(5.);
// "Pop" items from the queue in FIFO order
console .printLine(queue .pop().); // 1
console .printLine(queue .pop().); // 3
console .printLine(queue .pop().); // 5
// To tell if the queue is empty, we check the count
console .printLine("queue is ",(queue length.Length == 0) .iif("empty","nonempty")).;
// If we try to pop from an empty queue, an exception
// is thrown.
queue .pop() |\\ if(on::(e)[{ console .writeLine:("Queue empty.".) ].}
}</syntaxhighlight>
]</lang>
 
=={{header|Elisa}}==
Line 777 ⟶ 1,229:
=={{header|Elixir}}==
Here a list is used as Queue.
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule Queue do
def empty?([]), do: true
Line 788 ⟶ 1,240:
def front([h|_]), do: h
end
</syntaxhighlight>
</lang>
Example:
<syntaxhighlight lang="text">
iex(2)> q = [1,2,3,4,5]
[1, 2, 3, 4, 5]
Line 805 ⟶ 1,257:
iex(8)> Queue.empty?(l)
true
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
All functions, from the shell:
<langsyntaxhighlight Erlanglang="erlang">1> Q = fifo:new().
{fifo,[],[]}
2> fifo:empty(Q).
Line 825 ⟶ 1,277:
8> fifo:pop(fifo:new()).
** exception error: 'empty fifo'
in function fifo:pop/1</langsyntaxhighlight>
 
Crashing is the normal expected behavior in Erlang: let it crash, a supervisor will take responsibility of restarting processes, or the caller will take care of it. Only program for the successful cases.
Line 831 ⟶ 1,283:
=={{header|Factor}}==
For this task, we'll use Factor's <code>deque</code> vocabulary (short for double-ended queue). The <code>deque</code> class is a mixin, one of whose instances is <code>dlist</code> (double-linked list). Hence, the deque protocol works with double-linked lists. When using a deque as a queue, the convention is to queue elements with <code>push-front</code> and deque them with <code>pop-back</code>.
<langsyntaxhighlight lang="factor">USING: combinators deques dlists kernel prettyprint ;
IN: rosetta-code.queue-usage
 
Line 843 ⟶ 1,295:
[ pop-back drop ] ! pop 3 (and discard)
[ deque-empty? . ] ! t
} cleave</langsyntaxhighlight>
Alternatively, batch operations can be used.
<langsyntaxhighlight lang="factor">DL{ } clone {
[ [ { 1 2 3 } ] dip push-all-front ] ! push all from sequence
[ . ] ! DL{ 3 2 1 }
[ [ drop ] slurp-deque ] ! pop and discard all
[ deque-empty? . ] ! t
} cleave</langsyntaxhighlight>
 
=={{header|Fantom}}==
Line 856 ⟶ 1,308:
Using definition of Queue in: [[Queue/Definition]] task.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 871 ⟶ 1,323:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 891 ⟶ 1,343:
And a Forth version using some new features of Forth 2012, dynamic memory allocation and a linked list can be seen here:<BR> http://rosettacode.org/wiki/Queue/Definition#Linked_list_version
 
<syntaxhighlight lang="text">: cqueue: ( n -- <text>)
create \ compile time: build the data structure in memory
dup
Line 922 ⟶ 1,374:
: ?full ( q -- ) cnt=msk? abort" queue is full" ;
: 1+! ( adr -- ) 1 swap +! ; \ increment contents of adr
: 1-! ( adr -- ) -1 swap +! ; \ decrement contents of adr
 
: qc@ ( queue -- char ) \ fetch next char in queue
Line 935 ⟶ 1,387:
r@ ->cnt 1+! \ incr. the counter
r@ head++
r@ ->data r> ->head @ + c! ; \ data+head = adr, and store the char</langsyntaxhighlight>
 
Create 2 Queues and test the operators at the Forth console interactively
Line 960 ⟶ 1,412:
=== Version for the [[FIFO#Linked_list_version|Linked List implementation]] ===
 
<langsyntaxhighlight lang="forth">
make-queue constant q1
make-queue constant q2
Line 977 ⟶ 1,429:
q2 dequeue .
q2 empty? .
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
 
<langsyntaxhighlight lang="fortran">module fifo_nodes
type fifo_node
integer :: datum
Line 1,014 ⟶ 1,466:
end do
 
end program FIFOTest</langsyntaxhighlight>
 
 
=={{header|FreeBASIC}}==
As FreeBASIC does not have a built-in Queue type, I am reusing the type I wrote for the [[Queue/Definition]] task:
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task
Line 1,046 ⟶ 1,497:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,067 ⟶ 1,518:
===With Queue/Definition code===
Solution using [[Queue/Definition#Go|package]] from the [[Queue/Definition]] task:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,105 ⟶ 1,556:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 1,122 ⟶ 1,573:
===With channels===
Go buffered channels are FIFO, and better, are concurrency-safe (if you have an application for that.) Code below is same as code above only with Go channels rather than the home made queue implementation. Note that you don't have to start concurrent goroutines to use channels, they are useful all on their own. Other differences worth noting: Buffered channels are not dynamically resizable. This is a good thing, as queues that can grow without limit allow ugly bugs that consume memory and grind to a halt. Also blocking operations (as seen here with push) are probably a bad idea with a single goroutine. Much safer to use non-blocking operations that handle success and failure (the way pop is done here.)
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,157 ⟶ 1,608:
}
}
}</langsyntaxhighlight>
===With linked lists===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,197 ⟶ 1,648:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
 
Solution:
<langsyntaxhighlight lang="groovy">def q = new LinkedList()</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">assert q.empty
println q
// "push" adds to end of "queue" list
Line 1,250 ⟶ 1,701:
println q
assert q.empty
assert q.poll() == null</langsyntaxhighlight>
 
Output:
Line 1,269 ⟶ 1,720:
Running the code from [[Queue/Definition#Haskell]] through GHC's interpreter.
 
<syntaxhighlight lang="haskell">
<lang Haskell>
Prelude> :l fifo.hs
[1 of 1] Compiling Main ( fifo.hs, interpreted )
Line 1,295 ⟶ 1,746:
*Main> v''''
Nothing
</syntaxhighlight>
</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon provide built-in queue and stack functions.
<langsyntaxhighlight Iconlang="icon">procedure main(arglist)
queue := []
write("Usage:\nqueue x x x - x - - - - -\n\t- pops elements\n\teverything else pushes")
Line 1,316 ⟶ 1,767:
procedure empty(X) #: fail if X is not empty
if *X = 0 then return
end</langsyntaxhighlight>
 
Sample output: <pre>queue - 1 3 4 5 6 - - - - - - - -
Line 1,349 ⟶ 1,800:
This is an interactive J session:
 
<langsyntaxhighlight lang="j"> queue=: conew 'fifo'
isEmpty__queue ''
1
Line 1,367 ⟶ 1,818:
7
isEmpty__queue ''
1</langsyntaxhighlight>
 
Using function-level FIFO queue implementation from [[FIFO#J|FIFO]]
 
This is an interactive J session:
<langsyntaxhighlight lang="j"> is_empty make_empty _
1
first_named_state =: push 9 onto make_empty _
Line 1,388 ⟶ 1,839:
7
is_empty pop pop pop this_state
1</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
LinkedList can always be used as a queue or stack, but not in conjunction with the Stack object provided by Java. To use a LinkedList as a stack, use the <tt>push</tt> and <tt>pop</tt> methods. A LinkedList can also be used as a double-ended queue (deque); LinkedList has implemented the Deque interface since Java 1.6+.
<langsyntaxhighlight lang="java">import java.util.LinkedList;
import java.util.Queue;
...
Line 1,405 ⟶ 1,856:
System.out.println(queue.remove()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false</langsyntaxhighlight>
 
You can also use "offer" and "poll" methods instead of "add" and "remove", respectively. They indicate errors with the return value instead of throwing an exception.
 
{{works with|Java|1.4}}
<langsyntaxhighlight lang="java">import java.util.LinkedList;
...
LinkedList queue = new LinkedList();
Line 1,420 ⟶ 1,871:
System.out.println(queue.removeFirst()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false</langsyntaxhighlight>
 
=={{header|JavaScript}}==
JavaScript arrays can be used as FIFOs.
<langsyntaxhighlight lang="javascript">var f = new Array();
print(f.length);
f.push(1,2); // can take multiple arguments
Line 1,433 ⟶ 1,884:
print(f.shift())
print(f.length == 0);
print(f.shift());</langsyntaxhighlight>
 
outputs:
Line 1,445 ⟶ 1,896:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using DataStructures
 
queue = Queue(String)
Line 1,451 ⟶ 1,902:
@show enqueue!(queue, "bar")
@show dequeue!(queue) # -> foo
@show dequeue!(queue) # -> bar</langsyntaxhighlight>
 
=={{header|Kotlin}}==
The related [[Queue/Definition]] task, where we wrote our own Queue class, intimated that we should use the language's built-in queue for this task so that's what I'm going to do here, using Java collection types as Kotlin doesn't have a Queue type in its standard library:
<langsyntaxhighlight lang="scala">// version 1.1.2
 
import java.util.*
Line 1,476 ⟶ 1,927:
println("Can't remove elements from an empty queue")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,488 ⟶ 1,939:
Can't remove elements from an empty queue
</pre>
 
=={{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}}==
Line 1,497 ⟶ 1,985:
</pre>
Example:
<langsyntaxhighlight lang="lasso">
local(queue) = queue
#queue->size
Line 1,518 ⟶ 2,006:
#queue->size == 0
// => true
</syntaxhighlight>
</lang>
 
 
=={{header|Logo}}==
Line 1,525 ⟶ 2,012:
UCB Logo comes with a protocol for treating lists as queues.
 
<langsyntaxhighlight lang="logo">make "fifo []
print empty? :fifo ; true
queue "fifo 1
Line 1,533 ⟶ 2,020:
print dequeue "fifo ; 1
show :fifo ; [2 3]
print empty? :fifo ; false</langsyntaxhighlight>
 
=={{header|Lua}}==
Uses the queue-definition given at [[Queue/Definition#Lua]]
<langsyntaxhighlight lang="lua">q = Queue.new()
Queue.push( q, 5 )
Queue.push( q, "abc" )
Line 1,542 ⟶ 2,030:
while not Queue.empty( q ) do
print( Queue.pop( q ) )
end</langsyntaxhighlight>
 
One can also just use a regular Lua table (shown here in interactive mode):
 
<langsyntaxhighlight lang="lua">> -- create queue:
> q = {}
> -- push:
Line 1,561 ⟶ 2,049:
> -- empty?
> =#q == 0
true</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
M2000 has always a current stack object. We can define a new one using a pointer to a stack object (here the variable a). We can swap the currernt one with that on a, so Push, number, letter$ and Empty can be used on that object. Also we can use functions using the stack object as first parameter like stackitem(), stackitem$() and stacktype$().
 
 
<syntaxhighlight lang="m2000 interpreter">
Module CheckStackAsLIFO {
a=stack
Stack a {
Push 1, 2, 3
Print number=3
Print number=2
Print number=1
Print Empty=True
Push "A", "B", "C"
Print letter$="C"
Print letter$="B"
Print letter$="A"
Print Empty=True
Push 1,"OK"
}
Print Len(a)=2, StackItem(a, 2)=1, StackItem$(a, 1)="OK"
Print StackType$(a, 1)="String", StackType$(a,2)="Number"
}
CheckStackAsLIFO
Module CheckStackAsFIFO {
a=stack
Stack a {
Data 1, 2, 3
Print number=1
Print number=2
Print number=3
Print Empty=True
Data "A", "B", "C"
Print letter$="A"
Print letter$="B"
Print letter$="C"
Print Empty=True
Push 1,"OK"
}
Print Len(a)=2, StackItem(a, 2)=1, StackItem$(a, 1)="OK"
Print StackType$(a, 1)="String", StackType$(a,2)="Number"
}
CheckStackAsFIFO
</syntaxhighlight>
 
=={{header|Maple}}==
There are more builtin operations like reverse(), length(),etc.
<langsyntaxhighlight Maplelang="maple">q := queue[new]();
queue[enqueue](q,1);
queue[enqueue](q,2);
Line 1,578 ⟶ 2,111:
>>>3
queue[empty](q);
>>>true</langsyntaxhighlight>
 
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Empty[a_] := If[Length[a] == 0, True, False]
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]
Line 1,597 ⟶ 2,129:
->1
Pop[Queue]
->False</langsyntaxhighlight>
 
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace contains an implementation of a Queue.
<langsyntaxhighlight Nemerlelang="nemerle">mutable q = Queue(); // or use immutable version as per Haskell example
def empty = q.IsEmpty(); // true at this point
q.Push(empty); // or Enqueue(), or Add()
def a = q.Pop(); // or Dequeue() or Take()</langsyntaxhighlight>
 
=={{header|NetRexx}}==
Line 1,610 ⟶ 2,142:
 
The demonstration employs an in-line deployment of a queue object having as it's underlying implementation a <code>java.util.Deque</code> interface instanciated as a <code>java.util.ArrayDeque</code>. Typically this queue implementation would reside outside of the demonstration program and be imported at run-time rather than within the body of this source.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 1,675 ⟶ 2,207:
method isFalse public constant binary returns boolean
return \isTrue
</syntaxhighlight>
</lang>
;Output
<pre>
Line 1,686 ⟶ 2,218:
 
=={{header|Nim}}==
Nim standard library no longer provides a “queues” module, but it provides the more powerful module “deques” which allows to manage FIFO and stacks. Internally, this module uses a sequence and, thus, is more efficient than a linked list implementation.
<lang nim>import queues
 
When popping from an empty list, the module raises an IndexDefect which, as defect, is considered to be non catchable. In fact, by default, with version 1.4 of Nim the defects are still catchable but this may (will) change in some next version. The option <code>--panics:on|off</code> allows to control this behavior. Here, we have chosen to not try to catch the exception and the program terminates in error when trying to pop a fourth element from the queue.
var deq: TQueue[int] = initQueue[int]()
 
<syntaxhighlight lang="nim">import deques
deq.enqueue(26)
 
deq.add(99) # same as enqueue()
var queue = initDeque[int]()
deq.enqueue(2)
 
echo("Dequeue size: ", deq.len())
echo("De-queue: ", deq.dequeueaddLast()26)
echo("De-queue: ", deq.dequeueaddLast()99)
echo("De-queue: ", deq.dequeueaddLast()2)
echo "Queue size: ", queue.len()
#echo("De-queue: ", deq.dequeue()) # dequeue an empty dequeue raises [EAssertionFailed]</lang>
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()</syntaxhighlight>
{{out}}
<pre>DequeueQueue size: 3
De-queuePopping: 26
De-queuePopping: 99
Popping: 2
De-queue: 2</pre>
/home/lse/Documents/nim/Rosetta/queue_usage.nim(13) queue_usage
/home/lse/.choosenim/toolchains/nim-1.4.4/lib/pure/collections/deques.nim(113) popFirst
Error: unhandled exception: Empty deque. [IndexDefect]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 1,720 ⟶ 2,259:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml"># let q = Queue.create ();;
val q : '_a Queue.t = <abstr>
# Queue.is_empty q;;
Line 1,759 ⟶ 2,298:
- : int = 4
# Queue.is_empty q;;
- : bool = true</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,765 ⟶ 2,304:
Using FIFO implementation :
 
<langsyntaxhighlight lang="oforth">: testQueue
| q i |
Queue new ->q
20 loop: i [ i q push ]
while ( q empty not ) [ q pop . ] ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
ooRexx includes a built-in queue class.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
q = .queue~new -- create an instance
q~queue(3) -- adds to the end, but this is at the front
Line 1,779 ⟶ 2,318:
q~queue(2) -- add to the end
say q~pull q~pull q~pull q~isempty -- should display all and be empty
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,786 ⟶ 2,325:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
[Queue] = {Link ['x-oz://system/adt/Queue.ozf']}
MyQueue = {Queue.new}
Line 1,797 ⟶ 2,336:
{Show {MyQueue.get}} %% foo
{Show {MyQueue.get}} %% bar
{Show {MyQueue.get}} %% baz</langsyntaxhighlight>
 
=={{header|Perl}}==
Perl has built-in support to these operations:
<langsyntaxhighlight lang="perl">@queue = (); # we will simulate a queue in a array
 
push @queue, (1..5); # enqueue numbers from 1 to 5
Line 1,811 ⟶ 2,350:
print $n while($n = shift @queue); # dequeue all
print "\n";
print "array is empty\n" unless @queue; # is empty ?</langsyntaxhighlight>
Output:
<syntaxhighlight lang="text">1
2345
array is empty</langsyntaxhighlight>
 
=={{header|Perl 6}}==
 
Perl 6 maintains the same list operators of Perl, for this task, the operations are:
<lang>push (aka enqueue) -- @list.push
pop (aka dequeue) -- @list.shift
empty -- !@list.elems</lang>
but there's also @list.pop which removes a item from the end,
and @list.unshift which add a item on the start of the list.<br/>
Example:
<lang perl6>my @queue = < a >;
 
@queue.push('b', 'c'); # [ a, b, c ]
 
say @queue.shift; # a
say @queue.pop; # c
 
say @queue.perl; # [ b ]
say @queue.elems; # 1
 
@queue.unshift('A'); # [ A, b ]
@queue.push('C'); # [ A, b, C ]</lang>
 
=={{header|Phix}}==
Using the implementation from [[Queue/Definition#Phix|Queue/Definition]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>?empty() -- 1
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
push(5)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"empty:%t\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">empty</span><span style="color: #0000FF;">())</span> <span style="color: #000080;font-style:italic;">-- true</span>
?empty() -- 0
<span style="color: #000000;">push_item</span><span style="color: #0000FF;">(</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
push(6)
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"empty:%t\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">empty</span><span style="color: #0000FF;">())</span> <span style="color: #000080;font-style:italic;">-- false</span>
?pop() -- 5
<span style="color: #000000;">push_item</span><span style="color: #0000FF;">(</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
?pop() -- 6
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"pop_item:%v\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pop_item</span><span style="color: #0000FF;">())</span> <span style="color: #000080;font-style:italic;">-- 5</span>
?empty() -- 1</lang>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"pop_item:%v\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pop_item</span><span style="color: #0000FF;">())</span> <span style="color: #000080;font-style:italic;">-- 6</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"empty:%t\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">empty</span><span style="color: #0000FF;">())</span> <span style="color: #000080;font-style:italic;">-- true</span>
<!--</syntaxhighlight>-->
Using the builtins (same output):
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">queue</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_queue</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"empty:%t\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">queue_empty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">push</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"empty:%t\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">queue_empty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">push</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"pop:%v\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">pop</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"pop:%v\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">pop</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"empty:%t\n"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">queue_empty</span><span style="color: #0000FF;">(</span><span style="color: #000000;">queue</span><span style="color: #0000FF;">))</span>
<!--</syntaxhighlight>-->
 
=={{header|PHP}}==
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?php
$queue = new SplQueue;
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true
Line 1,860 ⟶ 2,392:
echo $queue->dequeue(), "\n"; // returns 1
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // returns false
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Using the implementation from [[FIFO]]:
<langsyntaxhighlight PicoLisplang="picolisp">(println (fifo 'Queue)) # Retrieve the number '1'
(println (fifo 'Queue)) # Retrieve an internal symbol 'abc'
(println (fifo 'Queue)) # Retrieve a transient symbol "abc"
(println (fifo 'Queue)) # and a list (abc)
(println (fifo 'Queue)) # Queue is empty -> NIL</langsyntaxhighlight>
Output:
<pre>1
Line 1,877 ⟶ 2,409:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
test: proc options (main);
 
Line 1,918 ⟶ 2,450:
end;
end test;
</syntaxhighlight>
</lang>
The output:
<syntaxhighlight lang="text">
1
3
Line 1,942 ⟶ 2,474:
17
19
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
[1 2 3 4 5] 6 exch tadd
= [1 2 3 4 5 6]
Line 1,953 ⟶ 2,485:
[] empty?
=true
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Line 1,959 ⟶ 2,491:
{{works with|PowerShell|4.0}}
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
[System.Collections.ArrayList]$queue = @()
# isEmpty?
Line 1,986 ⟶ 2,518:
}
"the queue contains : $queue"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,002 ⟶ 2,534:
===PowerShell using the .NET Queue Class===
Declare a new queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue = New-Object -TypeName System.Collections.Queue
#or
$queue = [System.Collections.Queue] @()
</syntaxhighlight>
</lang>
Show the methods and properties of the queue object:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-Member -InputObject $queue
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,036 ⟶ 2,568:
</pre>
Put some stuff in the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
1,2,3 | ForEach-Object {$queue.Enqueue($_)}
</syntaxhighlight>
</lang>
Take a peek at the head of the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Peek()
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,048 ⟶ 2,580:
</pre>
Pop the head of the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Dequeue()
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,056 ⟶ 2,588:
</pre>
Clear the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Clear()
</syntaxhighlight>
</lang>
Test if queue is empty:
<syntaxhighlight lang="powershell">
<lang PowerShell>
if (-not $queue.Count) {"Queue is empty"}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,071 ⟶ 2,603:
Works with SWI-Prolog.
 
<langsyntaxhighlight Prologlang="prolog">%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% definitions of queue
empty(U-V) :-
Line 2,119 ⟶ 2,651:
write('Pop the queue : '),
pop(Q4, _V, _Q5).
</syntaxhighlight>
</lang>
Output :
<pre>?- queue.
Line 2,135 ⟶ 2,667:
false.
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">NewList MyStack()
 
Procedure Push(n)
Line 2,172 ⟶ 2,705:
Debug Pop()
Wend
</syntaxhighlight>
</lang>
 
'''Outputs
Line 2,182 ⟶ 2,715:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import Queue
my_queue = Queue.Queue()
my_queue.put("foo")
Line 2,189 ⟶ 2,722:
print my_queue.get() # foo
print my_queue.get() # bar
print my_queue.get() # baz</langsyntaxhighlight>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ [] ] is queue ( --> q )
 
[ nested join ] is push ( q x --> q )
 
[ behead ] is pop ( q --> q x )
 
[ [] = ] is empty? ( q --> b )</syntaxhighlight>
'''Demonstrating operations in Quackery shell:'''
<pre>/O> queue
... 1 push
... $ "two" push
... ' [ 1 2 + echo say "rd" ] push
... say "The queue is " dup empty? not if [ say "not " ] say "empty." cr
... pop echo cr
... pop echo$ cr
... pop do cr
... say "The queue is " empty? not if [ say "not " ] say "empty." cr
...
The queue is not empty.
1
two
3rd
The queue is empty.
 
Stack empty.</pre>
 
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(require data/queue)
Line 2,208 ⟶ 2,769:
(dequeue! queue) ; 'green
 
(queue-empty? queue) ; #t</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Raku maintains the same list operators of Perl 5, for this task, the operations are:
<syntaxhighlight lang="text">push (aka enqueue) -- @list.push
pop (aka dequeue) -- @list.shift
empty -- !@list.elems</syntaxhighlight>
but there's also @list.pop which removes a item from the end,
and @list.unshift which add a item on the start of the list.<br/>
Example:
<syntaxhighlight lang="raku" line>my @queue = < a >;
 
@queue.push('b', 'c'); # [ a, b, c ]
 
say @queue.shift; # a
say @queue.pop; # c
 
say @queue; # [ b ]
say @queue.elems; # 1
 
@queue.unshift('A'); # [ A, b ]
@queue.push('C'); # [ A, b, C ]</syntaxhighlight>
 
=={{header|REBOL}}==
Line 2,214 ⟶ 2,798:
See [[FIFO#REBOL]] for implementation. Example repeated here for completeness.
 
<langsyntaxhighlight REBOLlang="rebol">; Create and populate a FIFO:
 
q: make fifo []
Line 2,228 ⟶ 2,812:
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>
 
Output:
Line 2,257 ⟶ 2,841:
 
The entries in the stack may be anything, including "nulls".
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates four queueing operations: push, pop, empty, query. */
say '══════════════════════════════════ Pushing five values to the stack.'
do j=1 for 4 /*a DO loop to PUSH four values. */
Line 2,278 ⟶ 2,862:
push: queue arg(1); return /*(The REXX QUEUE is FIFO.) */
pop: procedure; parse pull x; return x /*REXX PULL removes a stack item. */
empty: return queued()==0 /*returns the status of the stack. */</langsyntaxhighlight>
{{out|output|text=:}}
<pre>
Line 2,299 ⟶ 2,883:
 
=={{header|Ruby}}==
Sample usage at [[FIFO#Ruby]].<p>
Or use the built-in Queue class:
 
<syntaxhighlight lang="ruby">q = Queue.new
q.push "Hello" # .enq is an alias
q.push "world"
p q.pop # .deq is an alias
p q.empty? # => false
</syntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::collections::VecDeque;
 
fn main() {
let mut queue = VecDeque::new();
queue.push_back("Hello");
queue.push_back("World");
while let Some(item) = queue.pop_front() {
println!("{}", item);
}
 
if queue.is_empty() {
println!("Yes, it is empty!");
}
}
</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">val q=scala.collection.mutable.Queue[Int]()
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
Line 2,312 ⟶ 2,921:
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)</langsyntaxhighlight>
Output:
<pre>isEmpty = true
Line 2,324 ⟶ 2,933:
=={{header|Sidef}}==
Using the class defined at [[FIFO#Sidef]]
<langsyntaxhighlight lang="ruby">var f = FIFO();
say f.empty; # true
f.push('foo');
Line 2,333 ⟶ 2,942:
var g = FIFO('xxx', 'yyy');
say g.pop; # xxx
say f.pop; # bar</langsyntaxhighlight>
 
=={{header|Standard ML}}==
{{works with|SML/NJ}}
; Functional interface
<langsyntaxhighlight lang="sml">- open Fifo;
opening Fifo
datatype 'a fifo = ...
Line 2,385 ⟶ 2,994:
val v''' = 4 : int
- isEmpty q'''''';
val it = true : bool</langsyntaxhighlight>
 
{{works with|SML/NJ}}
; Imperative interface
<langsyntaxhighlight lang="sml">- open Queue;
opening Queue
type 'a queue
Line 2,443 ⟶ 3,052:
val it = 4 : int
- isEmpty q;
val it = true : bool</langsyntaxhighlight>
 
=={{header|Stata}}==
See [[Singly-linked list/Element definition#Stata]].
 
=={{header|Tcl}}==
See [[FIFO#Tcl|FIFO]] for operation implementations:
<langsyntaxhighlight lang="tcl">set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
Line 2,456 ⟶ 3,066:
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
See [[Queue/Definition#UNIX_Shell|Queue/Definition]] for implementation:
<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 2,474 ⟶ 3,084:
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>
 
Output:
Line 2,484 ⟶ 3,094:
peek:
queue foo is empty</pre>
 
=={{header|VBA}}==
See [[Queue/Definition#VBA]] for implementation.
The FiFo queue has been implemented with Collection. queue.count will return number of items in the queue. queue(i) will return the i-th item in the queue.
<syntaxhighlight lang="vb">Public Sub fifo()
push "One"
push "Two"
push "Three"
Debug.Print pop, pop, pop, empty_
End Sub</syntaxhighlight>{{out}}
<pre>One Two Three True</pre>
 
=={{header|Wart}}==
Line 2,499 ⟶ 3,120:
len q
=> 1</pre>
 
=={{header|Wren}}==
{{libheader|Wren-queue}}
<syntaxhighlight lang="wren">import "./queue" for Queue
 
var q = Queue.new()
q.push(1)
q.push(2)
System.print("Queue contains %(q)")
System.print("Number of elements in queue = %(q.count)")
var item = q.pop()
System.print("'%(item)' popped from the queue")
System.print("First element is now %(q.peek())")
q.clear()
System.print("Queue cleared")
System.print("Is queue now empty? %((q.isEmpty) ? "yes" : "no")")</syntaxhighlight>
 
{{out}}
<pre>
Queue contains [1, 2]
Number of elements in queue = 2
'1' popped from the queue
First element is now 2
Queue cleared
Is queue now empty? yes
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
def Size=8;
int Fifo(Size);
Line 2,548 ⟶ 3,195:
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
]</langsyntaxhighlight>
 
Output:
Line 2,565 ⟶ 3,212:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub push(x$)
queue$ = queue$ + x$ + "#"
end sub
Line 2,605 ⟶ 3,252:
wend
 
print "Pop ", pop$()</langsyntaxhighlight>
 
{{out}}
1,995

edits