Queue/Usage: Difference between revisions
m
→{{header|EasyLang}}
(46 intermediate revisions by 27 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}}==
<
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>
=={{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}}==
<
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;</
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'''<
MODE DIETITEM = STRUCT(
STRING food, annual quantity, units, REAL cost
Line 73 ⟶ 330:
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
)</
# -*- coding: utf-8 -*- #
Line 92 ⟶ 349:
# OR example queue ISNT obj queue empty #
printf((diet item fmt, obj queue get(example queue), $l$))
OD</
<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}}==
<
set StackRef's contents to {value} & StackRef's contents
return StackRef
Line 133 ⟶ 410:
pop(a reference to theStack)
log result
end repeat</
(*2, 1*)
(*3, 2, 1*)
Line 145 ⟶ 422:
</pre>
=={{header|
<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
]
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}}==
<
my_queue.push!
my_queue.push!
my_queue.push!
print my_queue.pop!() # 'foo'
print my_queue.pop!() # 'bar'
print my_queue.pop!() # 'baz'</syntaxhighlight>
=={{header|AutoHotkey}}==
<
MsgBox % "Len = " len("qu") ; Number of entries
Line 208 ⟶ 510:
StringReplace %queue%, %queue%, |, |, UseErrorLevel
Return %queue% = "" ? 0 : ErrorLevel+1
}</
=={{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|
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
<
FOR n = 3 TO 5
Line 242 ⟶ 602:
= (rptr% = wptr%)
ENDCASE
ENDPROC</
'''Output:'''
<pre>
Line 261 ⟶ 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
<
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
Line 298 ⟶ 658:
| out$"Attempt to dequeue failed"
)
;</
Output:
<pre>1
Line 310 ⟶ 670:
=={{header|C}}==
See [[FIFO]] for the needed code.
<
#include <stdlib.h>
#include <stdbool.h>
Line 340 ⟶ 700:
exit(0);
}</
=={{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>.
<
#include <cassert> // for run time assertions
Line 389 ⟶ 789:
q.pop();
assert( q.empty() );
}</
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
<
(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|Clojure}}==
Using the implementation from [[FIFO]]:
<
(enqueue q 1)
Line 448 ⟶ 808:
(dequeue q) ; 3
(queue-empty? q) ; true</
Or use a java implementation:
<
(.add q 1)
Line 460 ⟶ 820:
(.remove q) ; 3
(.isEmpty q) ; true</
=={{header|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 496 ⟶ 856:
catch e
console.log "#{e}"
</syntaxhighlight>
output
<syntaxhighlight lang="text">
> coffee queue.coffee
1
100000
Error: queue is empty
</syntaxhighlight>
=={{header|Common Lisp}}==
Using the implementation from [[FIFO]].
<
(enqueue 38 queue)
(assert (not (queue-empty-p queue)))
Line 514 ⟶ 874:
(assert (eql 38 (dequeue queue)))
(assert (eql 23 (dequeue queue)))
(assert (queue-empty-p queue)))</
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE UseQueue;
IMPORT
Queue,
Boxes,
StdLog;
PROCEDURE Do*;
VAR
StdLog.String("Is empty:> ");StdLog.Bool(q.IsEmpty());StdLog.Ln
END Do;
END UseQueue.
</syntaxhighlight>
Execute: ^Q UseQueue.Do<br/>
Output:
Line 547 ⟶ 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}}==
<
private static struct Node {
T data;
Line 591 ⟶ 992:
assert(q.pop() == 30);
assert(q.empty());
}</
===Faster Version===
This versions creates a circular queue able to grow. Define "queue_usage2_main" to run the main and its tests.
<
import std.traits: hasIndirections;
Line 669 ⟶ 1,070:
}
}
}</
=={{header|Delphi}}==
Generics were added in Delphi2009.
<
{$APPTYPE CONSOLE}
Line 698 ⟶ 1,099:
lStringQueue.Free;
end
end.</
Output:
Line 705 ⟶ 1,106:
Third
Queue is empty.</pre>
=={{header|Déjà Vu}}==
This uses the definition from [[Queue/Definition#Déjà Vu]]
<
!. empty Q
enqueue Q "HELLO"
Line 717 ⟶ 1,119:
!. dequeue Q
!. empty Q
!. dequeue Q</
{{out}}
<pre>true
Line 729 ⟶ 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]].
<
require(escape empty { reader.dequeue(empty); false } catch _ { true })
writer.enqueue(1)
Line 741 ⟶ 1,178:
require(reader.dequeue(throw) == 2)
require(reader.dequeue(throw) == 3)
require(escape empty { reader.dequeue(empty); false } catch _ { true })</
E also has queues in the standard library such as <code><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
<
import extensions
public program()
{
// Create a queue and "push" items into it
var queue :=
queue
queue
queue
// "Pop" items from the queue in FIFO order
console
console
console
// To tell if the queue is empty, we check the count
console
// If we try to pop from an empty queue, an exception
// is thrown.
queue
}</syntaxhighlight>
=={{header|Elisa}}==
Line 776 ⟶ 1,229:
=={{header|Elixir}}==
Here a list is used as Queue.
<syntaxhighlight lang="elixir">
defmodule Queue do
def empty?([]), do: true
Line 787 ⟶ 1,240:
def front([h|_]), do: h
end
</syntaxhighlight>
Example:
<syntaxhighlight lang="text">
iex(2)> q = [1,2,3,4,5]
[1, 2, 3, 4, 5]
Line 804 ⟶ 1,257:
iex(8)> Queue.empty?(l)
true
</syntaxhighlight>
=={{header|Erlang}}==
All functions, from the shell:
<
{fifo,[],[]}
2> fifo:empty(Q).
Line 824 ⟶ 1,277:
8> fifo:pop(fifo:new()).
** exception error: 'empty fifo'
in function fifo:pop/1</
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 830 ⟶ 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>.
<
IN: rosetta-code.queue-usage
Line 842 ⟶ 1,295:
[ pop-back drop ] ! pop 3 (and discard)
[ deque-empty? . ] ! t
} cleave</
Alternatively, batch operations can be used.
<
[ [ { 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</
=={{header|Fantom}}==
Line 855 ⟶ 1,308:
Using definition of Queue in: [[Queue/Definition]] task.
<
class Main
{
Line 870 ⟶ 1,323:
}
}
</syntaxhighlight>
Output:
Line 890 ⟶ 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 921 ⟶ 1,374:
: ?full ( q -- ) cnt=msk? abort" queue is full" ;
: 1+! ( adr -- ) 1 swap +! ; \ increment contents of adr
: 1-! ( adr -- ) -1 swap +! ;
: qc@ ( queue -- char ) \ fetch next char in queue
Line 934 ⟶ 1,387:
r@ ->cnt 1+! \ incr. the counter
r@ head++
r@ ->data r> ->head @ + c! ; \ data+head = adr, and store the char</
Create 2 Queues and test the operators at the Forth console interactively
Line 959 ⟶ 1,412:
=== Version for the [[FIFO#Linked_list_version|Linked List implementation]] ===
<
make-queue constant q1
make-queue constant q2
Line 976 ⟶ 1,429:
q2 dequeue .
q2 empty? .
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
type fifo_node
integer :: datum
Line 1,013 ⟶ 1,466:
end do
end program FIFOTest</
=={{header|FreeBASIC}}==
As FreeBASIC does not have a built-in Queue type, I am reusing the type I wrote for the [[Queue/Definition]] task:
<
#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task
Line 1,045 ⟶ 1,497:
Print
Print "Press any key to quit"
Sleep</
{{out}}
Line 1,066 ⟶ 1,518:
===With Queue/Definition code===
Solution using [[Queue/Definition#Go|package]] from the [[Queue/Definition]] task:
<
import (
Line 1,104 ⟶ 1,556:
}
}
}</
Output:
<pre>
Line 1,121 ⟶ 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.)
<
import "fmt"
Line 1,156 ⟶ 1,608:
}
}
}</
===With linked lists===
<
import (
Line 1,196 ⟶ 1,648:
}
}
}</
=={{header|Groovy}}==
Solution:
<
Test:
<
println q
// "push" adds to end of "queue" list
Line 1,249 ⟶ 1,701:
println q
assert q.empty
assert q.poll() == null</
Output:
Line 1,268 ⟶ 1,720:
Running the code from [[Queue/Definition#Haskell]] through GHC's interpreter.
<syntaxhighlight lang="haskell">
Prelude> :l fifo.hs
[1 of 1] Compiling Main ( fifo.hs, interpreted )
Line 1,294 ⟶ 1,746:
*Main> v''''
Nothing
</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon provide built-in queue and stack functions.
<
queue := []
write("Usage:\nqueue x x x - x - - - - -\n\t- pops elements\n\teverything else pushes")
Line 1,315 ⟶ 1,767:
procedure empty(X) #: fail if X is not empty
if *X = 0 then return
end</
Sample output: <pre>queue - 1 3 4 5 6 - - - - - - - -
Line 1,348 ⟶ 1,800:
This is an interactive J session:
<
isEmpty__queue ''
1
Line 1,366 ⟶ 1,818:
7
isEmpty__queue ''
1</
Using function-level FIFO queue implementation from [[FIFO#J|FIFO]]
This is an interactive J session:
<
1
first_named_state =: push 9 onto make_empty _
Line 1,387 ⟶ 1,839:
7
is_empty pop pop pop this_state
1</
=={{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+.
<
import java.util.Queue;
...
Line 1,404 ⟶ 1,856:
System.out.println(queue.remove()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false</
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}}
<
...
LinkedList queue = new LinkedList();
Line 1,419 ⟶ 1,871:
System.out.println(queue.removeFirst()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false</
=={{header|JavaScript}}==
JavaScript arrays can be used as FIFOs.
<
print(f.length);
f.push(1,2); // can take multiple arguments
Line 1,432 ⟶ 1,884:
print(f.shift())
print(f.length == 0);
print(f.shift());</
outputs:
Line 1,444 ⟶ 1,896:
{{works with|Julia|0.6}}
<
queue = Queue(String)
Line 1,450 ⟶ 1,902:
@show enqueue!(queue, "bar")
@show dequeue!(queue) # -> foo
@show dequeue!(queue) # -> bar</
=={{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:
<
import java.util.*
Line 1,475 ⟶ 1,927:
println("Can't remove elements from an empty queue")
}
}</
{{out}}
Line 1,487 ⟶ 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,496 ⟶ 1,985:
</pre>
Example:
<
local(queue) = queue
#queue->size
Line 1,517 ⟶ 2,006:
#queue->size == 0
// => true
</syntaxhighlight>
=={{header|Logo}}==
Line 1,524 ⟶ 2,012:
UCB Logo comes with a protocol for treating lists as queues.
<
print empty? :fifo ; true
queue "fifo 1
Line 1,532 ⟶ 2,020:
print dequeue "fifo ; 1
show :fifo ; [2 3]
print empty? :fifo ; false</
=={{header|Lua}}==
Uses the queue-definition given at [[Queue/Definition#Lua]]
<
Queue.push( q, 5 )
Queue.push( q, "abc" )
Line 1,541 ⟶ 2,030:
while not Queue.empty( q ) do
print( Queue.pop( q ) )
end</
One can also just use a regular Lua table (shown here in interactive mode):
<
> q = {}
> -- push:
Line 1,560 ⟶ 2,049:
> -- empty?
> =#q == 0
true</
=={{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.
<
queue[enqueue](q,1);
queue[enqueue](q,2);
Line 1,577 ⟶ 2,111:
>>>3
queue[empty](q);
>>>true</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
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,596 ⟶ 2,129:
->1
Pop[Queue]
->False</
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace contains an implementation of a Queue.
<
def empty = q.IsEmpty(); // true at this point
q.Push(empty); // or Enqueue(), or Add()
def a = q.Pop(); // or Dequeue() or Take()</
=={{header|NetRexx}}==
Line 1,609 ⟶ 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.
<
options replace format comments java crossref savelog symbols nobinary
Line 1,674 ⟶ 2,207:
method isFalse public constant binary returns boolean
return \isTrue
</syntaxhighlight>
;Output
<pre>
Line 1,685 ⟶ 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.
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.
<syntaxhighlight lang="nim">import deques
var queue = initDeque[int]()
echo "Queue size: ", queue.len()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()</syntaxhighlight>
{{out}}
<pre>
Popping: 2
/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}}==
<
class Test {
function : Main(args : String[]) ~ Nil {
Line 1,719 ⟶ 2,259:
}
}
</syntaxhighlight>
=={{header|OCaml}}==
<
val q : '_a Queue.t = <abstr>
# Queue.is_empty q;;
Line 1,758 ⟶ 2,298:
- : int = 4
# Queue.is_empty q;;
- : bool = true</
=={{header|Oforth}}==
Line 1,764 ⟶ 2,304:
Using FIFO implementation :
<
| q i |
Queue new ->q
20 loop: i [ i q push ]
while ( q empty not ) [ q pop . ] ;</
=={{header|ooRexx}}==
ooRexx includes a built-in queue class.
<syntaxhighlight lang="oorexx">
q = .queue~new -- create an instance
q~queue(3) -- adds to the end, but this is at the front
Line 1,778 ⟶ 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>
Output:
<pre>
Line 1,785 ⟶ 2,325:
=={{header|Oz}}==
<
[Queue] = {Link ['x-oz://system/adt/Queue.ozf']}
MyQueue = {Queue.new}
Line 1,796 ⟶ 2,336:
{Show {MyQueue.get}} %% foo
{Show {MyQueue.get}} %% bar
{Show {MyQueue.get}} %% baz</
=={{header|Perl}}==
Perl has built-in support to these operations:
<
push @queue, (1..5); # enqueue numbers from 1 to 5
Line 1,810 ⟶ 2,350:
print $n while($n = shift @queue); # dequeue all
print "\n";
print "array is empty\n" unless @queue; # is empty ?</
Output:
<syntaxhighlight lang="text">1
2345
array is empty</
=={{header|Phix}}==
Using the implementation from [[Queue/Definition#Phix|Queue/Definition]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</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>
<span style="color: #000000;">push_item</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: #000000;">empty</span><span style="color: #0000FF;">())</span> <span style="color: #000080;font-style:italic;">-- false</span>
<span style="color: #000000;">push_item</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_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>
<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+}}
<
$queue = new SplQueue;
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true
Line 1,859 ⟶ 2,392:
echo $queue->dequeue(), "\n"; // returns 1
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // returns false
?></
=={{header|PicoLisp}}==
Using the implementation from [[FIFO]]:
<
(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</
Output:
<pre>1
Line 1,876 ⟶ 2,409:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
test: proc options (main);
Line 1,917 ⟶ 2,450:
end;
end test;
</syntaxhighlight>
The output:
<syntaxhighlight lang="text">
1
3
Line 1,941 ⟶ 2,474:
17
19
</syntaxhighlight>
=={{header|PostScript}}==
{{libheader|initlib}}
<
[1 2 3 4 5] 6 exch tadd
= [1 2 3 4 5 6]
Line 1,952 ⟶ 2,485:
[] empty?
=true
</syntaxhighlight>
=={{header|PowerShell}}==
Line 1,958 ⟶ 2,491:
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
[System.Collections.ArrayList]$queue = @()
# isEmpty?
Line 1,985 ⟶ 2,518:
}
"the queue contains : $queue"
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 2,001 ⟶ 2,534:
===PowerShell using the .NET Queue Class===
Declare a new queue:
<syntaxhighlight lang="powershell">
$queue = New-Object -TypeName System.Collections.Queue
#or
$queue = [System.Collections.Queue] @()
</syntaxhighlight>
Show the methods and properties of the queue object:
<syntaxhighlight lang="powershell">
Get-Member -InputObject $queue
</syntaxhighlight>
{{Out}}
<pre>
Line 2,035 ⟶ 2,568:
</pre>
Put some stuff in the queue:
<syntaxhighlight lang="powershell">
1,2,3 | ForEach-Object {$queue.Enqueue($_)}
</syntaxhighlight>
Take a peek at the head of the queue:
<syntaxhighlight lang="powershell">
$queue.Peek()
</syntaxhighlight>
{{Out}}
<pre>
Line 2,047 ⟶ 2,580:
</pre>
Pop the head of the queue:
<syntaxhighlight lang="powershell">
$queue.Dequeue()
</syntaxhighlight>
{{Out}}
<pre>
Line 2,055 ⟶ 2,588:
</pre>
Clear the queue:
<syntaxhighlight lang="powershell">
$queue.Clear()
</syntaxhighlight>
Test if queue is empty:
<syntaxhighlight lang="powershell">
if (-not $queue.Count) {"Queue is empty"}
</syntaxhighlight>
{{Out}}
<pre>
Line 2,070 ⟶ 2,603:
Works with SWI-Prolog.
<
%% definitions of queue
empty(U-V) :-
Line 2,118 ⟶ 2,651:
write('Pop the queue : '),
pop(Q4, _V, _Q5).
</syntaxhighlight>
Output :
<pre>?- queue.
Line 2,134 ⟶ 2,667:
false.
</pre>
=={{header|PureBasic}}==
<
Procedure Push(n)
Line 2,171 ⟶ 2,705:
Debug Pop()
Wend
</syntaxhighlight>
'''Outputs
Line 2,181 ⟶ 2,715:
=={{header|Python}}==
<
my_queue = Queue.Queue()
my_queue.put("foo")
Line 2,188 ⟶ 2,722:
print my_queue.get() # foo
print my_queue.get() # bar
print my_queue.get() # baz</
=={{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}}==
<
(require data/queue)
Line 2,207 ⟶ 2,769:
(dequeue! queue) ; 'green
(queue-empty? queue) ; #t</
=={{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,213 ⟶ 2,798:
See [[FIFO#REBOL]] for implementation. Example repeated here for completeness.
<
q: make fifo []
Line 2,227 ⟶ 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]</
Output:
Line 2,256 ⟶ 2,841:
The entries in the stack may be anything, including "nulls".
<
say '══════════════════════════════════ Pushing five values to the stack.'
do j=1 for 4 /*a DO loop to PUSH four values.
call push j * 10 /*PUSH (aka: enqueue to the stack).
say 'pushed value:' j * 10 /*echo the pushed value. */
if j\==3 then iterate /*
call push /*PUSH (aka: enqueue to the stack).
say 'pushed a "null" value.' /*echo what was pushed
end /*j*/
say '══════════════════════════════════ Quering the stack (number of entries).'
say queued() ' entries in the stack.'
say '══════════════════════════════════ Popping all values from the stack.'
do
call pop /*POP (aka: dequeue from the stack).*/
say
end /*
say '══════════════════════════════════ The stack is now empty.'
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
push: queue arg(1);
pop: procedure; parse pull x; return x /*REXX PULL removes a stack item. */
empty: return queued()==0 /*returns the status of the stack. */</
<pre>
══════════════════════════════════ Pushing five values to the stack.
Line 2,284 ⟶ 2,871:
pushed a "null" value.
pushed value: 40
══════════════════════════════════ Quering the stack (number of entries).
5 entries in the stack.
══════════════════════════════════ Popping all values from the stack.
1: popped value= 10
Line 2,294 ⟶ 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}}==
<
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
Line 2,307 ⟶ 2,921:
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)</
Output:
<pre>isEmpty = true
Line 2,319 ⟶ 2,933:
=={{header|Sidef}}==
Using the class defined at [[FIFO#Sidef]]
<
say f.empty; # true
f.push('foo');
Line 2,328 ⟶ 2,942:
var g = FIFO('xxx', 'yyy');
say g.pop; # xxx
say f.pop; # bar</
=={{header|Standard ML}}==
{{works with|SML/NJ}}
; Functional interface
<
opening Fifo
datatype 'a fifo = ...
Line 2,380 ⟶ 2,994:
val v''' = 4 : int
- isEmpty q'''''';
val it = true : bool</
{{works with|SML/NJ}}
; Imperative interface
<
opening Queue
type 'a queue
Line 2,438 ⟶ 3,052:
val it = 4 : int
- isEmpty q;
val it = true : bool</
=={{header|Stata}}==
See [[Singly-linked list/Element definition#Stata]].
=={{header|Tcl}}==
See [[FIFO#Tcl|FIFO]] for operation implementations:
<
empty Q ;# ==> 1 (true)
push Q foo
Line 2,451 ⟶ 3,066:
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar</
=={{header|UNIX Shell}}==
{{works with|ksh93}}
See [[Queue/Definition#UNIX_Shell|Queue/Definition]] for implementation:
<
queue_empty foo && echo foo is empty || echo foo is not empty
Line 2,469 ⟶ 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</
Output:
Line 2,479 ⟶ 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,494 ⟶ 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}}==
<
def Size=8;
int Fifo(Size);
Line 2,543 ⟶ 3,195:
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
]</
Output:
Line 2,558 ⟶ 3,210:
3
</pre>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">sub push(x$)
queue$ = queue$ + x$ + "#"
end sub
sub pop$()
local i, r$
if queue$ <> "" then
i = instr(queue$, "#")
if i then
r$ = left$(queue$, i-1)
stack$ = right$(queue$, len(queue$) - i)
else
r$ = queue$
queue$ = ""
end if
return r$
else
print "--Queue is empty--"
end if
end sub
sub empty()
return queue$ = ""
end sub
// ======== test ========
for n = 3 to 5
print "Push ", n : push(str$(n))
next
print "Pop ", pop$()
print "Push ", 6 : push(str$(6))
while(not empty())
print "Pop ", pop$()
wend
print "Pop ", pop$()</syntaxhighlight>
{{out}}
<pre>Push 3
Push 4
Push 5
Pop 3
Push 6
Pop 4
Pop 5
Pop 6
Pop --Queue is empty--</pre>
=={{header|zkl}}==
|