Queue/Usage: Difference between revisions

m
No edit summary
 
(25 intermediate revisions by 16 users not shown)
Line 18:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">Deque[String] my_queue
 
my_queue.append(‘foo’)
Line 26:
print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())</langsyntaxhighlight>
 
{{out}}
Line 33:
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 44 ⟶ 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 67 ⟶ 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 78 ⟶ 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 92 ⟶ 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 111 ⟶ 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 144 ⟶ 382:
 
=={{header|AppleScript}}==
<langsyntaxhighlight AppleScriptlang="applescript ">on push(StackRef, value)
set StackRef's contents to {value} & StackRef's contents
return StackRef
Line 172 ⟶ 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 186 ⟶ 424:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="arturo">Queuedefine :queue #{[][
init: [
list #()
this\items: []
]
]
 
empty?: function [this :queue][
push {
listzero? list+&this\items
]
}
 
push: function [this :queue, item][
pop {
this\items: this\items ++ item
if $(empty) {
]
panic "trying to pop from an empty queue!"
}
 
pop: function [this :queue][
first_item $(first list)
ensure -> not? empty? this
list $(deleteBy list 0)
return first_item
result: this\items\0
}
this\items: remove.index this\items 0
return result
]
 
Q: to :queue []
empty {
$(size list)=0
}
 
push Q 1
inspect {
push Q 2
log this
push Q }3
}
 
print ["queue is empty?" empty? Q]
q $(new ~Queue)
 
print ["popping:" pop Q]
q.push "one"
print ["popping:" pop Q]
q.push "two"
print ["popping:" pop Q]
q.push "three"
 
print ["queue is empty?" empty? Q]</syntaxhighlight>
q.inspect
 
print "popped = " + $(q.pop)
print "is it empty? = " + $(q.empty)</lang>
 
{{out}}
 
<pre>queue is empty? false
<pre>#{
popping: 1
empty <function: 0x1093917A0>
popping: 2
inspect <function: 0x109391800>
popping: 3
list #(
queue is empty? true</pre>
"one"
"two"
"three"
)
pop <function: 0x109391740>
push <function: 0x1093916E0>
}
popped = one
is it empty? = false</pre>
 
=={{header|Astro}}==
<langsyntaxhighlight lang="python">let my_queue = Queue()
 
my_queue.push!('foo')
Line 248 ⟶ 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 281 ⟶ 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 315 ⟶ 602:
= (rptr% = wptr%)
ENDCASE
ENDPROC</langsyntaxhighlight>
'''Output:'''
<pre>
Line 334 ⟶ 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 371 ⟶ 658:
| out$"Attempt to dequeue failed"
)
;</langsyntaxhighlight>
Output:
<pre>1
Line 383 ⟶ 670:
=={{header|C}}==
See [[FIFO]] for the needed code.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 413 ⟶ 700:
 
exit(0);
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
In C# we can use the Queue<T> class in the .NET 2.0 framework.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 453 ⟶ 740:
}
}
}</langsyntaxhighlight>
 
=={{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 502 ⟶ 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>.
Line 511 ⟶ 798:
=={{header|Clojure}}==
Using the implementation from [[FIFO]]:
<langsyntaxhighlight lang="lisp">(def q (make-queue))
 
(enqueue q 1)
Line 521 ⟶ 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 533 ⟶ 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 569 ⟶ 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 587 ⟶ 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
Line 615 ⟶ 902:
END Do;
END UseQueue.
</syntaxhighlight>
</lang>
Execute: ^Q UseQueue.Do<br/>
Output:
Line 627 ⟶ 914:
in a file named <code>queue.coh</code>.
 
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
typedef QueueData is uint8; # the queue will contain bytes
Line 654 ⟶ 941:
 
# free the queue
FreeQueue(queue);</langsyntaxhighlight>
 
{{out}}
Line 662 ⟶ 949:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">class LinkedQueue(T) {
private static struct Node {
T data;
Line 705 ⟶ 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 783 ⟶ 1,070:
}
}
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Generics were added in Delphi2009.
 
<langsyntaxhighlight Delphilang="delphi">program QueueUsage;
 
{$APPTYPE CONSOLE}
Line 812 ⟶ 1,099:
lStringQueue.Free;
end
end.</langsyntaxhighlight>
 
Output:
Line 822 ⟶ 1,109:
=={{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 832 ⟶ 1,119:
!. dequeue Q
!. empty Q
!. dequeue Q</langsyntaxhighlight>
{{out}}
<pre>true
Line 844 ⟶ 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 856 ⟶ 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 46.x :
<langsyntaxhighlight lang="elena">import system'collections;
import extensions;
Line 870 ⟶ 1,207:
var queue := new Queue();
queue.push:(1);
queue.push:(3);
queue.push:(5);
// "Pop" items from the queue in FIFO order
Line 884 ⟶ 1,221:
// If we try to pop from an empty queue, an exception
// is thrown.
queue.pop() |\\ on::(e){ console.writeLine:("Queue empty.") }
}</langsyntaxhighlight>
 
=={{header|Elisa}}==
Line 892 ⟶ 1,229:
=={{header|Elixir}}==
Here a list is used as Queue.
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule Queue do
def empty?([]), do: true
Line 903 ⟶ 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 920 ⟶ 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 940 ⟶ 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 946 ⟶ 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 958 ⟶ 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 971 ⟶ 1,308:
Using definition of Queue in: [[Queue/Definition]] task.
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 986 ⟶ 1,323:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,006 ⟶ 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 1,050 ⟶ 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 1,075 ⟶ 1,412:
=== Version for the [[FIFO#Linked_list_version|Linked List implementation]] ===
 
<langsyntaxhighlight lang="forth">
make-queue constant q1
make-queue constant q2
Line 1,092 ⟶ 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,129 ⟶ 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,160 ⟶ 1,497:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,181 ⟶ 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,219 ⟶ 1,556:
}
}
}</langsyntaxhighlight>
Output:
<pre>
Line 1,236 ⟶ 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,271 ⟶ 1,608:
}
}
}</langsyntaxhighlight>
===With linked lists===
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,311 ⟶ 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,364 ⟶ 1,701:
println q
assert q.empty
assert q.poll() == null</langsyntaxhighlight>
 
Output:
Line 1,383 ⟶ 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,409 ⟶ 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,430 ⟶ 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,463 ⟶ 1,800:
This is an interactive J session:
 
<langsyntaxhighlight lang="j"> queue=: conew 'fifo'
isEmpty__queue ''
1
Line 1,481 ⟶ 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,502 ⟶ 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,519 ⟶ 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,534 ⟶ 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,547 ⟶ 1,884:
print(f.shift())
print(f.length == 0);
print(f.shift());</langsyntaxhighlight>
 
outputs:
Line 1,559 ⟶ 1,896:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">using DataStructures
 
queue = Queue(String)
Line 1,565 ⟶ 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,590 ⟶ 1,927:
println("Can't remove elements from an empty queue")
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,602 ⟶ 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,611 ⟶ 1,985:
</pre>
Example:
<langsyntaxhighlight lang="lasso">
local(queue) = queue
#queue->size
Line 1,632 ⟶ 2,006:
#queue->size == 0
// => true
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
Line 1,638 ⟶ 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,646 ⟶ 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,656 ⟶ 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,675 ⟶ 2,049:
> -- empty?
> =#q == 0
true</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 1,681 ⟶ 2,055:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckStackAsQueueCheckStackAsLIFO {
a=stack
Stack a {
Line 1,700 ⟶ 2,074:
Print StackType$(a, 1)="String", StackType$(a,2)="Number"
}
CheckStackAsLIFO
CheckStackAsQueue
Module CheckStackAsFIFO {
</lang>
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,718 ⟶ 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,736 ⟶ 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,749 ⟶ 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,814 ⟶ 2,207:
method isFalse public constant binary returns boolean
return \isTrue
</syntaxhighlight>
</lang>
;Output
<pre>
Line 1,825 ⟶ 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.
 
<syntaxhighlight lang="nim">import deques
 
var deq: TQueue[int]queue = initQueueinitDeque[int]()
 
deqqueue.enqueueaddLast(26)
queue.addLast(99)
deq.add(99) # same as enqueue()
deqqueue.enqueueaddLast(2)
echo( "DequeueQueue size: ", deqqueue.len())
echo( "De-queuePopping: ", deqqueue.dequeuepopFirst())
echo( "De-queuePopping: ", deqqueue.dequeuepopFirst())
echo( "De-queuePopping: ", deqqueue.dequeuepopFirst())
echo "Popping: ", queue.popFirst()</syntaxhighlight>
#echo("De-queue: ", deq.dequeue()) # dequeue an empty dequeue raises [EAssertionFailed]</lang>
{{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,859 ⟶ 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,898 ⟶ 2,298:
- : int = 4
# Queue.is_empty q;;
- : bool = true</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,904 ⟶ 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,918 ⟶ 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,925 ⟶ 2,325:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
[Queue] = {Link ['x-oz://system/adt/Queue.ozf']}
MyQueue = {Queue.new}
Line 1,936 ⟶ 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,950 ⟶ 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|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,977 ⟶ 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,994 ⟶ 2,409:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
test: proc options (main);
 
Line 2,035 ⟶ 2,450:
end;
end test;
</syntaxhighlight>
</lang>
The output:
<syntaxhighlight lang="text">
1
3
Line 2,059 ⟶ 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 2,070 ⟶ 2,485:
[] empty?
=true
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Line 2,076 ⟶ 2,491:
{{works with|PowerShell|4.0}}
 
<syntaxhighlight lang="powershell">
<lang PowerShell>
[System.Collections.ArrayList]$queue = @()
# isEmpty?
Line 2,103 ⟶ 2,518:
}
"the queue contains : $queue"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,119 ⟶ 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,153 ⟶ 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,165 ⟶ 2,580:
</pre>
Pop the head of the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Dequeue()
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,173 ⟶ 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,188 ⟶ 2,603:
Works with SWI-Prolog.
 
<langsyntaxhighlight Prologlang="prolog">%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% definitions of queue
empty(U-V) :-
Line 2,236 ⟶ 2,651:
write('Pop the queue : '),
pop(Q4, _V, _Q5).
</syntaxhighlight>
</lang>
Output :
<pre>?- queue.
Line 2,254 ⟶ 2,669:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">NewList MyStack()
 
Procedure Push(n)
Line 2,290 ⟶ 2,705:
Debug Pop()
Wend
</syntaxhighlight>
</lang>
 
'''Outputs
Line 2,300 ⟶ 2,715:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import Queue
my_queue = Queue.Queue()
my_queue.put("foo")
Line 2,307 ⟶ 2,722:
print my_queue.get() # foo
print my_queue.get() # bar
print my_queue.get() # baz</langsyntaxhighlight>
 
=={{header|Quackery}}==
<langsyntaxhighlight Quackerylang="quackery">[ [] ] is queue ( --> q )
 
[ nested join ] is push ( q x --> q )
Line 2,316 ⟶ 2,731:
[ behead ] is pop ( q --> q x )
 
[ [] = ] is empty? ( q --> b )</langsyntaxhighlight>
'''Demonstrating operations in Quackery shell:'''
<pre>/O> queue
Line 2,338 ⟶ 2,753:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(require data/queue)
Line 2,354 ⟶ 2,769:
(dequeue! queue) ; 'green
 
(queue-empty? queue) ; #t</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,360 ⟶ 2,775:
 
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</langsyntaxhighlight>
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" perl6line>my @queue = < a >;
 
@queue.push('b', 'c'); # [ a, b, c ]
Line 2,377 ⟶ 2,792:
 
@queue.unshift('A'); # [ A, b ]
@queue.push('C'); # [ A, b, C ]</langsyntaxhighlight>
 
=={{header|REBOL}}==
Line 2,383 ⟶ 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,397 ⟶ 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,426 ⟶ 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,447 ⟶ 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,468 ⟶ 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}}==
<langsyntaxhighlight lang="rust">use std::collections::VecDeque;
 
fn main() {
Line 2,485 ⟶ 2,908:
}
}
</syntaxhighlight>
</lang>
 
=={{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,498 ⟶ 2,921:
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)</langsyntaxhighlight>
Output:
<pre>isEmpty = true
Line 2,510 ⟶ 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,519 ⟶ 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,571 ⟶ 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,629 ⟶ 3,052:
val it = 4 : int
- isEmpty q;
val it = true : bool</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 2,636 ⟶ 3,059:
=={{header|Tcl}}==
See [[FIFO#Tcl|FIFO]] for operation implementations:
<langsyntaxhighlight lang="tcl">set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
Line 2,643 ⟶ 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,661 ⟶ 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,675 ⟶ 3,098:
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.
<langsyntaxhighlight lang="vb">Public Sub fifo()
push "One"
push "Two"
push "Three"
Debug.Print pop, pop, pop, empty_
End Sub</langsyntaxhighlight>{{out}}
<pre>One Two Three True</pre>
 
Line 2,700 ⟶ 3,123:
=={{header|Wren}}==
{{libheader|Wren-queue}}
<langsyntaxhighlight ecmascriptlang="wren">import "./queue" for Queue
 
var q = Queue.new()
Line 2,712 ⟶ 3,135:
q.clear()
System.print("Queue cleared")
System.print("Is queue now empty? %((q.isEmpty) ? "yes" : "no")")</langsyntaxhighlight>
 
{{out}}
Line 2,725 ⟶ 3,148:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
def Size=8;
int Fifo(Size);
Line 2,772 ⟶ 3,195:
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
]</langsyntaxhighlight>
 
Output:
Line 2,789 ⟶ 3,212:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">sub push(x$)
queue$ = queue$ + x$ + "#"
end sub
Line 2,829 ⟶ 3,252:
wend
 
print "Pop ", pop$()</langsyntaxhighlight>
 
{{out}}
1,980

edits