Queue/Usage: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 18: Line 18:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>Deque[String] my_queue
<syntaxhighlight lang="11l">Deque[String] my_queue


my_queue.append(‘foo’)
my_queue.append(‘foo’)
Line 26: Line 26:
print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())</lang>
print(my_queue.pop_left())</syntaxhighlight>


{{out}}
{{out}}
Line 38: Line 38:




<lang 6502asm>
<syntaxhighlight lang="6502asm">
queuePointerStart equ #$FD
queuePointerStart equ #$FD
queuePointerMinus1 equ #$FC ;make this equal whatever "queuePointerStart" is, minus 1.
queuePointerMinus1 equ #$FC ;make this equal whatever "queuePointerStart" is, minus 1.
Line 72: Line 72:


yes:
yes:
RTS</lang>
RTS</syntaxhighlight>


===PUSH===
===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>.
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>.


<lang 6502asm>define temp $00
<syntaxhighlight lang="6502asm">define temp $00
define queueEmpty $FD
define queueEmpty $FD
define queueAlmostEmpty $FC
define queueAlmostEmpty $FC
Line 92: Line 92:
jsr pushQueue
jsr pushQueue


brk</lang>
brk</syntaxhighlight>


Output of Example 1:
Output of Example 1:
Line 103: Line 103:
</pre>
</pre>
===POP===
===POP===
<lang 6502asm>define temp $00
<syntaxhighlight lang="6502asm">define temp $00
define queueEmpty $FD
define queueEmpty $FD
define queueAlmostEmpty $FC
define queueAlmostEmpty $FC
Line 120: Line 120:
jsr popQueue
jsr popQueue


brk</lang>
brk</syntaxhighlight>


Output of Example 2:
Output of Example 2:
Line 133: Line 133:
===PUSH,POP,PUSH===
===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.
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.
<lang 6502asm>define temp $00
<syntaxhighlight lang="6502asm">define temp $00
define queueEmpty $FD
define queueEmpty $FD
define queueAlmostEmpty $FC
define queueAlmostEmpty $FC
Line 154: Line 154:
jsr pushQueue
jsr pushQueue


brk</lang>
brk</syntaxhighlight>


Output of Example 3:
Output of Example 3:
Line 164: Line 164:


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang="forth">
10 q:new \ create a new queue 10 deep
10 q:new \ create a new queue 10 deep
123 q:push
123 q:push
Line 172: Line 172:
q:pop . cr \ displays 341
q:pop . cr \ displays 341
q:len . cr \ displays 0
q:len . cr \ displays 0
</syntaxhighlight>
</lang>


=={{header|Action!}}==
=={{header|Action!}}==
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
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}}
{{libheader|Action! Tool Kit}}
<lang Action!>CARD EndProg ;required for ALLOCATE.ACT
<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!
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 262: Line 262:
TestIsEmpty()
TestIsEmpty()
TestPop()
TestPop()
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
Error at the end of the program is intentional.
Error at the end of the program is intentional.
Line 285: Line 285:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with FIFO;
<syntaxhighlight lang="ada">with FIFO;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;
Line 305: Line 305:
Pop (Queue, Value);
Pop (Queue, Value);
Put_Line ("Is_Empty " & Boolean'Image (Is_Empty (Queue)));
Put_Line ("Is_Empty " & Boolean'Image (Is_Empty (Queue)));
end Queue_Test;</lang>
end Queue_Test;</syntaxhighlight>
Sample output:
Sample output:
<pre>Is_Empty TRUE</pre>
<pre>Is_Empty TRUE</pre>
Line 316: Line 316:
'''File: prelude/link.a68''' c.f. [[Queue/Definition#ALGOL 68|Queue/Definition]]<br>
'''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: prelude/queue_base.a68''' c.f. [[Queue/Definition#ALGOL 68|Queue/Definition]]<br>
'''File: test/data_stigler_diet.a68'''<lang algol68># -*- coding: utf-8 -*- #
'''File: test/data_stigler_diet.a68'''<syntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
MODE DIETITEM = STRUCT(
MODE DIETITEM = STRUCT(
STRING food, annual quantity, units, REAL cost
STRING food, annual quantity, units, REAL cost
Line 330: Line 330:
("Wheat Flour", "370","lb.", 13.33),
("Wheat Flour", "370","lb.", 13.33),
("Total Annual Cost", "","", 39.93)
("Total Annual Cost", "","", 39.93)
)</lang>'''File: test/queue.a68'''<lang algol68>#!/usr/bin/a68g --script #
)</syntaxhighlight>'''File: test/queue.a68'''<syntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
# -*- coding: utf-8 -*- #


Line 349: Line 349:
# OR example queue ISNT obj queue empty #
# OR example queue ISNT obj queue empty #
printf((diet item fmt, obj queue get(example queue), $l$))
printf((diet item fmt, obj queue get(example queue), $l$))
OD</lang>'''Output:'''
OD</syntaxhighlight>'''Output:'''
<pre>
<pre>
Get remaining values from queue:
Get remaining values from queue:
Line 382: Line 382:


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript >on push(StackRef, value)
<syntaxhighlight lang="applescript ">on push(StackRef, value)
set StackRef's contents to {value} & StackRef's contents
set StackRef's contents to {value} & StackRef's contents
return StackRef
return StackRef
Line 410: Line 410:
pop(a reference to theStack)
pop(a reference to theStack)
log result
log result
end repeat</lang>Output (in Script Editor Event Log):<pre> (*1*)
end repeat</syntaxhighlight>Output (in Script Editor Event Log):<pre> (*1*)
(*2, 1*)
(*2, 1*)
(*3, 2, 1*)
(*3, 2, 1*)
Line 423: Line 423:


=={{header|Astro}}==
=={{header|Astro}}==
<lang python>let my_queue = Queue()
<syntaxhighlight lang="python">let my_queue = Queue()


my_queue.push!('foo')
my_queue.push!('foo')
Line 431: Line 431:
print my_queue.pop!() # 'foo'
print my_queue.pop!() # 'foo'
print my_queue.pop!() # 'bar'
print my_queue.pop!() # 'bar'
print my_queue.pop!() # 'baz'</lang>
print my_queue.pop!() # 'baz'</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST
<syntaxhighlight lang="autohotkey">push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST


MsgBox % "Len = " len("qu") ; Number of entries
MsgBox % "Len = " len("qu") ; Number of entries
Line 464: Line 464:
StringReplace %queue%, %queue%, |, |, UseErrorLevel
StringReplace %queue%, %queue%, |, |, UseErrorLevel
Return %queue% = "" ? 0 : ErrorLevel+1
Return %queue% = "" ? 0 : ErrorLevel+1
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>function deque(arr) {
<syntaxhighlight lang="awk">function deque(arr) {
arr["start"] = 0
arr["start"] = 0
arr["end"] = 0
arr["end"] = 0
Line 521: Line 521:
}
}
printdeque(q)
printdeque(q)
}</lang>
}</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> FIFOSIZE = 1000
<syntaxhighlight lang="bbcbasic"> FIFOSIZE = 1000
FOR n = 3 TO 5
FOR n = 3 TO 5
Line 555: Line 555:
= (rptr% = wptr%)
= (rptr% = wptr%)
ENDCASE
ENDCASE
ENDPROC</lang>
ENDPROC</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>
<pre>
Line 574: Line 574:


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
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
<lang bracmat> ( queue
<syntaxhighlight lang="bracmat"> ( queue
= (list=)
= (list=)
(enqueue=.(.!arg) !(its.list):?(its.list))
(enqueue=.(.!arg) !(its.list):?(its.list))
Line 611: Line 611:
| out$"Attempt to dequeue failed"
| out$"Attempt to dequeue failed"
)
)
;</lang>
;</syntaxhighlight>
Output:
Output:
<pre>1
<pre>1
Line 623: Line 623:
=={{header|C}}==
=={{header|C}}==
See [[FIFO]] for the needed code.
See [[FIFO]] for the needed code.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdbool.h>
Line 653: Line 653:


exit(0);
exit(0);
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==
In C# we can use the Queue<T> class in the .NET 2.0 framework.
In C# we can use the Queue<T> class in the .NET 2.0 framework.
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 693: Line 693:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{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>.
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>.
<lang cpp>#include <queue>
<syntaxhighlight lang="cpp">#include <queue>
#include <cassert> // for run time assertions
#include <cassert> // for run time assertions


Line 742: Line 742:
q.pop();
q.pop();
assert( q.empty() );
assert( q.empty() );
}</lang>
}</syntaxhighlight>


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
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
<lang cpp> std::queue<int, std::list<int> ></lang>
<syntaxhighlight lang="cpp"> std::queue<int, std::list<int> ></syntaxhighlight>


(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>.
(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 751: Line 751:
=={{header|Clojure}}==
=={{header|Clojure}}==
Using the implementation from [[FIFO]]:
Using the implementation from [[FIFO]]:
<lang lisp>(def q (make-queue))
<syntaxhighlight lang="lisp">(def q (make-queue))


(enqueue q 1)
(enqueue q 1)
Line 761: Line 761:
(dequeue q) ; 3
(dequeue q) ; 3


(queue-empty? q) ; true</lang>
(queue-empty? q) ; true</syntaxhighlight>
Or use a java implementation:
Or use a java implementation:
<lang lisp>(def q (java.util.LinkedList.))
<syntaxhighlight lang="lisp">(def q (java.util.LinkedList.))


(.add q 1)
(.add q 1)
Line 773: Line 773:
(.remove q) ; 3
(.remove q) ; 3


(.isEmpty q) ; true</lang>
(.isEmpty q) ; true</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
<lang coffeescript>
<syntaxhighlight lang="coffeescript">
# We build a Queue on top of an ordinary JS array, which supports push
# 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
# and shift. For simple queues, it might make sense to just use arrays
Line 809: Line 809:
catch e
catch e
console.log "#{e}"
console.log "#{e}"
</syntaxhighlight>
</lang>
output
output
<lang>
<syntaxhighlight lang="text">
> coffee queue.coffee
> coffee queue.coffee
1
1
100000
100000
Error: queue is empty
Error: queue is empty
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Using the implementation from [[FIFO]].
Using the implementation from [[FIFO]].


<lang lisp>(let ((queue (make-queue)))
<syntaxhighlight lang="lisp">(let ((queue (make-queue)))
(enqueue 38 queue)
(enqueue 38 queue)
(assert (not (queue-empty-p queue)))
(assert (not (queue-empty-p queue)))
Line 827: Line 827:
(assert (eql 38 (dequeue queue)))
(assert (eql 38 (dequeue queue)))
(assert (eql 23 (dequeue queue)))
(assert (eql 23 (dequeue queue)))
(assert (queue-empty-p queue)))</lang>
(assert (queue-empty-p queue)))</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE UseQueue;
MODULE UseQueue;
IMPORT
IMPORT
Line 855: Line 855:
END Do;
END Do;
END UseQueue.
END UseQueue.
</syntaxhighlight>
</lang>
Execute: ^Q UseQueue.Do<br/>
Execute: ^Q UseQueue.Do<br/>
Output:
Output:
Line 867: Line 867:
in a file named <code>queue.coh</code>.
in a file named <code>queue.coh</code>.


<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


typedef QueueData is uint8; # the queue will contain bytes
typedef QueueData is uint8; # the queue will contain bytes
Line 894: Line 894:


# free the queue
# free the queue
FreeQueue(queue);</lang>
FreeQueue(queue);</syntaxhighlight>


{{out}}
{{out}}
Line 902: Line 902:


=={{header|D}}==
=={{header|D}}==
<lang d>class LinkedQueue(T) {
<syntaxhighlight lang="d">class LinkedQueue(T) {
private static struct Node {
private static struct Node {
T data;
T data;
Line 945: Line 945:
assert(q.pop() == 30);
assert(q.pop() == 30);
assert(q.empty());
assert(q.empty());
}</lang>
}</syntaxhighlight>


===Faster Version===
===Faster Version===
This versions creates a circular queue able to grow. Define "queue_usage2_main" to run the main and its tests.
This versions creates a circular queue able to grow. Define "queue_usage2_main" to run the main and its tests.
<lang d>module queue_usage2;
<syntaxhighlight lang="d">module queue_usage2;


import std.traits: hasIndirections;
import std.traits: hasIndirections;
Line 1,023: Line 1,023:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Generics were added in Delphi2009.
Generics were added in Delphi2009.


<lang Delphi>program QueueUsage;
<syntaxhighlight lang="delphi">program QueueUsage;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,052: Line 1,052:
lStringQueue.Free;
lStringQueue.Free;
end
end
end.</lang>
end.</syntaxhighlight>


Output:
Output:
Line 1,062: Line 1,062:
=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
This uses the definition from [[Queue/Definition#Déjà Vu]]
This uses the definition from [[Queue/Definition#Déjà Vu]]
<lang dejavu>local :Q queue
<syntaxhighlight lang="dejavu">local :Q queue
!. empty Q
!. empty Q
enqueue Q "HELLO"
enqueue Q "HELLO"
Line 1,072: Line 1,072:
!. dequeue Q
!. dequeue Q
!. empty Q
!. empty Q
!. dequeue Q</lang>
!. dequeue Q</syntaxhighlight>
{{out}}
{{out}}
<pre>true
<pre>true
Line 1,087: Line 1,087:
=={{header|Diego}}==
=={{header|Diego}}==
Diego has a <code>queue</code> object and posit:
Diego has a <code>queue</code> object and posit:
<lang diego>set_ns(rosettacode)_me();
<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)
add_queue({int},q)_values(1..4); // 1,2,3,4 (1 is first/bottom, 4 is last/top)
Line 1,117: Line 1,117:
me_msg()_queue(q)_history()_all(); // returns the entire history of queue 'q' since its creation
me_msg()_queue(q)_history()_all(); // returns the entire history of queue 'q' since its creation


reset_namespace[];</lang>
reset_namespace[];</syntaxhighlight>
<code>queue</code> is a derivative of <code>array</code>, so arrays can also be used as queues.
<code>queue</code> is a derivative of <code>array</code>, so arrays can also be used as queues.


Line 1,123: Line 1,123:
Using the implementation from [[FIFO]].
Using the implementation from [[FIFO]].


<lang e>def [reader, writer] := makeQueue()
<syntaxhighlight lang="e">def [reader, writer] := makeQueue()
require(escape empty { reader.dequeue(empty); false } catch _ { true })
require(escape empty { reader.dequeue(empty); false } catch _ { true })
writer.enqueue(1)
writer.enqueue(1)
Line 1,131: Line 1,131:
require(reader.dequeue(throw) == 2)
require(reader.dequeue(throw) == 2)
require(reader.dequeue(throw) == 3)
require(reader.dequeue(throw) == 3)
require(escape empty { reader.dequeue(empty); false } catch _ { true })</lang>
require(escape empty { reader.dequeue(empty); false } catch _ { true })</syntaxhighlight>


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.
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.
Line 1,137: Line 1,137:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'collections;
<syntaxhighlight lang="elena">import system'collections;
import extensions;
import extensions;
Line 1,160: Line 1,160:
// is thrown.
// is thrown.
queue.pop() | on:(e){ console.writeLine:"Queue empty." }
queue.pop() | on:(e){ console.writeLine:"Queue empty." }
}</lang>
}</syntaxhighlight>


=={{header|Elisa}}==
=={{header|Elisa}}==
Line 1,167: Line 1,167:
=={{header|Elixir}}==
=={{header|Elixir}}==
Here a list is used as Queue.
Here a list is used as Queue.
<syntaxhighlight lang="elixir">
<lang Elixir>
defmodule Queue do
defmodule Queue do
def empty?([]), do: true
def empty?([]), do: true
Line 1,178: Line 1,178:
def front([h|_]), do: h
def front([h|_]), do: h
end
end
</syntaxhighlight>
</lang>
Example:
Example:
<lang>
<syntaxhighlight lang="text">
iex(2)> q = [1,2,3,4,5]
iex(2)> q = [1,2,3,4,5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Line 1,195: Line 1,195:
iex(8)> Queue.empty?(l)
iex(8)> Queue.empty?(l)
true
true
</syntaxhighlight>
</lang>


=={{header|Erlang}}==
=={{header|Erlang}}==
All functions, from the shell:
All functions, from the shell:
<lang Erlang>1> Q = fifo:new().
<syntaxhighlight lang="erlang">1> Q = fifo:new().
{fifo,[],[]}
{fifo,[],[]}
2> fifo:empty(Q).
2> fifo:empty(Q).
Line 1,215: Line 1,215:
8> fifo:pop(fifo:new()).
8> fifo:pop(fifo:new()).
** exception error: 'empty fifo'
** exception error: 'empty fifo'
in function fifo:pop/1</lang>
in function fifo:pop/1</syntaxhighlight>


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.
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 1,221: Line 1,221:
=={{header|Factor}}==
=={{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>.
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>.
<lang factor>USING: combinators deques dlists kernel prettyprint ;
<syntaxhighlight lang="factor">USING: combinators deques dlists kernel prettyprint ;
IN: rosetta-code.queue-usage
IN: rosetta-code.queue-usage


Line 1,233: Line 1,233:
[ pop-back drop ] ! pop 3 (and discard)
[ pop-back drop ] ! pop 3 (and discard)
[ deque-empty? . ] ! t
[ deque-empty? . ] ! t
} cleave</lang>
} cleave</syntaxhighlight>
Alternatively, batch operations can be used.
Alternatively, batch operations can be used.
<lang factor>DL{ } clone {
<syntaxhighlight lang="factor">DL{ } clone {
[ [ { 1 2 3 } ] dip push-all-front ] ! push all from sequence
[ [ { 1 2 3 } ] dip push-all-front ] ! push all from sequence
[ . ] ! DL{ 3 2 1 }
[ . ] ! DL{ 3 2 1 }
[ [ drop ] slurp-deque ] ! pop and discard all
[ [ drop ] slurp-deque ] ! pop and discard all
[ deque-empty? . ] ! t
[ deque-empty? . ] ! t
} cleave</lang>
} cleave</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==
Line 1,246: Line 1,246:
Using definition of Queue in: [[Queue/Definition]] task.
Using definition of Queue in: [[Queue/Definition]] task.


<lang fantom>
<syntaxhighlight lang="fantom">
class Main
class Main
{
{
Line 1,261: Line 1,261:
}
}
}
}
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,281: Line 1,281:
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
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


<lang>: cqueue: ( n -- <text>)
<syntaxhighlight lang="text">: cqueue: ( n -- <text>)
create \ compile time: build the data structure in memory
create \ compile time: build the data structure in memory
dup
dup
Line 1,325: Line 1,325:
r@ ->cnt 1+! \ incr. the counter
r@ ->cnt 1+! \ incr. the counter
r@ head++
r@ head++
r@ ->data r> ->head @ + c! ; \ data+head = adr, and store the char</lang>
r@ ->data r> ->head @ + c! ; \ data+head = adr, and store the char</syntaxhighlight>


Create 2 Queues and test the operators at the Forth console interactively
Create 2 Queues and test the operators at the Forth console interactively
Line 1,350: Line 1,350:
=== Version for the [[FIFO#Linked_list_version|Linked List implementation]] ===
=== Version for the [[FIFO#Linked_list_version|Linked List implementation]] ===


<lang forth>
<syntaxhighlight lang="forth">
make-queue constant q1
make-queue constant q1
make-queue constant q2
make-queue constant q2
Line 1,367: Line 1,367:
q2 dequeue .
q2 dequeue .
q2 empty? .
q2 empty? .
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}


<lang fortran>module fifo_nodes
<syntaxhighlight lang="fortran">module fifo_nodes
type fifo_node
type fifo_node
integer :: datum
integer :: datum
Line 1,404: Line 1,404:
end do
end do


end program FIFOTest</lang>
end program FIFOTest</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
As FreeBASIC does not have a built-in Queue type, I am reusing the type I wrote for the [[Queue/Definition]] task:
As FreeBASIC does not have a built-in Queue type, I am reusing the type I wrote for the [[Queue/Definition]] task:
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task
#Include "queue_rosetta.bi" '' include macro-based generic Queue type used in earlier task
Line 1,435: Line 1,435:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,456: Line 1,456:
===With Queue/Definition code===
===With Queue/Definition code===
Solution using [[Queue/Definition#Go|package]] from the [[Queue/Definition]] task:
Solution using [[Queue/Definition#Go|package]] from the [[Queue/Definition]] task:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,494: Line 1,494:
}
}
}
}
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,511: Line 1,511:
===With channels===
===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.)
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.)
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,546: Line 1,546:
}
}
}
}
}</lang>
}</syntaxhighlight>
===With linked lists===
===With linked lists===
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,586: Line 1,586:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==


Solution:
Solution:
<lang groovy>def q = new LinkedList()</lang>
<syntaxhighlight lang="groovy">def q = new LinkedList()</syntaxhighlight>


Test:
Test:
<lang groovy>assert q.empty
<syntaxhighlight lang="groovy">assert q.empty
println q
println q
// "push" adds to end of "queue" list
// "push" adds to end of "queue" list
Line 1,639: Line 1,639:
println q
println q
assert q.empty
assert q.empty
assert q.poll() == null</lang>
assert q.poll() == null</syntaxhighlight>


Output:
Output:
Line 1,658: Line 1,658:
Running the code from [[Queue/Definition#Haskell]] through GHC's interpreter.
Running the code from [[Queue/Definition#Haskell]] through GHC's interpreter.


<syntaxhighlight lang="haskell">
<lang Haskell>
Prelude> :l fifo.hs
Prelude> :l fifo.hs
[1 of 1] Compiling Main ( fifo.hs, interpreted )
[1 of 1] Compiling Main ( fifo.hs, interpreted )
Line 1,684: Line 1,684:
*Main> v''''
*Main> v''''
Nothing
Nothing
</syntaxhighlight>
</lang>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon and Unicon provide built-in queue and stack functions.
Icon and Unicon provide built-in queue and stack functions.
<lang Icon>procedure main(arglist)
<syntaxhighlight lang="icon">procedure main(arglist)
queue := []
queue := []
write("Usage:\nqueue x x x - x - - - - -\n\t- pops elements\n\teverything else pushes")
write("Usage:\nqueue x x x - x - - - - -\n\t- pops elements\n\teverything else pushes")
Line 1,705: Line 1,705:
procedure empty(X) #: fail if X is not empty
procedure empty(X) #: fail if X is not empty
if *X = 0 then return
if *X = 0 then return
end</lang>
end</syntaxhighlight>


Sample output: <pre>queue - 1 3 4 5 6 - - - - - - - -
Sample output: <pre>queue - 1 3 4 5 6 - - - - - - - -
Line 1,738: Line 1,738:
This is an interactive J session:
This is an interactive J session:


<lang j> queue=: conew 'fifo'
<syntaxhighlight lang="j"> queue=: conew 'fifo'
isEmpty__queue ''
isEmpty__queue ''
1
1
Line 1,756: Line 1,756:
7
7
isEmpty__queue ''
isEmpty__queue ''
1</lang>
1</syntaxhighlight>


Using function-level FIFO queue implementation from [[FIFO#J|FIFO]]
Using function-level FIFO queue implementation from [[FIFO#J|FIFO]]


This is an interactive J session:
This is an interactive J session:
<lang j> is_empty make_empty _
<syntaxhighlight lang="j"> is_empty make_empty _
1
1
first_named_state =: push 9 onto make_empty _
first_named_state =: push 9 onto make_empty _
Line 1,777: Line 1,777:
7
7
is_empty pop pop pop this_state
is_empty pop pop pop this_state
1</lang>
1</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{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+.
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+.
<lang java>import java.util.LinkedList;
<syntaxhighlight lang="java">import java.util.LinkedList;
import java.util.Queue;
import java.util.Queue;
...
...
Line 1,794: Line 1,794:
System.out.println(queue.remove()); // 1
System.out.println(queue.remove()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false</lang>
System.out.println(queue.isEmpty()); // false</syntaxhighlight>


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.
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}}
{{works with|Java|1.4}}
<lang java>import java.util.LinkedList;
<syntaxhighlight lang="java">import java.util.LinkedList;
...
...
LinkedList queue = new LinkedList();
LinkedList queue = new LinkedList();
Line 1,809: Line 1,809:
System.out.println(queue.removeFirst()); // 1
System.out.println(queue.removeFirst()); // 1
System.out.println(queue); // [2, 3]
System.out.println(queue); // [2, 3]
System.out.println(queue.isEmpty()); // false</lang>
System.out.println(queue.isEmpty()); // false</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
JavaScript arrays can be used as FIFOs.
JavaScript arrays can be used as FIFOs.
<lang javascript>var f = new Array();
<syntaxhighlight lang="javascript">var f = new Array();
print(f.length);
print(f.length);
f.push(1,2); // can take multiple arguments
f.push(1,2); // can take multiple arguments
Line 1,822: Line 1,822:
print(f.shift())
print(f.shift())
print(f.length == 0);
print(f.length == 0);
print(f.shift());</lang>
print(f.shift());</syntaxhighlight>


outputs:
outputs:
Line 1,834: Line 1,834:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>using DataStructures
<syntaxhighlight lang="julia">using DataStructures


queue = Queue(String)
queue = Queue(String)
Line 1,840: Line 1,840:
@show enqueue!(queue, "bar")
@show enqueue!(queue, "bar")
@show dequeue!(queue) # -> foo
@show dequeue!(queue) # -> foo
@show dequeue!(queue) # -> bar</lang>
@show dequeue!(queue) # -> bar</syntaxhighlight>


=={{header|Kotlin}}==
=={{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:
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:
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.util.*
import java.util.*
Line 1,865: Line 1,865:
println("Can't remove elements from an empty queue")
println("Can't remove elements from an empty queue")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,886: Line 1,886:
</pre>
</pre>
Example:
Example:
<lang lasso>
<syntaxhighlight lang="lasso">
local(queue) = queue
local(queue) = queue
#queue->size
#queue->size
Line 1,907: Line 1,907:
#queue->size == 0
#queue->size == 0
// => true
// => true
</syntaxhighlight>
</lang>


=={{header|Logo}}==
=={{header|Logo}}==
Line 1,913: Line 1,913:
UCB Logo comes with a protocol for treating lists as queues.
UCB Logo comes with a protocol for treating lists as queues.


<lang logo>make "fifo []
<syntaxhighlight lang="logo">make "fifo []
print empty? :fifo ; true
print empty? :fifo ; true
queue "fifo 1
queue "fifo 1
Line 1,921: Line 1,921:
print dequeue "fifo ; 1
print dequeue "fifo ; 1
show :fifo ; [2 3]
show :fifo ; [2 3]
print empty? :fifo ; false</lang>
print empty? :fifo ; false</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
Uses the queue-definition given at [[Queue/Definition#Lua]]
Uses the queue-definition given at [[Queue/Definition#Lua]]
<lang lua>q = Queue.new()
<syntaxhighlight lang="lua">q = Queue.new()
Queue.push( q, 5 )
Queue.push( q, 5 )
Queue.push( q, "abc" )
Queue.push( q, "abc" )
Line 1,931: Line 1,931:
while not Queue.empty( q ) do
while not Queue.empty( q ) do
print( Queue.pop( q ) )
print( Queue.pop( q ) )
end</lang>
end</syntaxhighlight>


One can also just use a regular Lua table (shown here in interactive mode):
One can also just use a regular Lua table (shown here in interactive mode):


<lang lua>> -- create queue:
<syntaxhighlight lang="lua">> -- create queue:
> q = {}
> q = {}
> -- push:
> -- push:
Line 1,950: Line 1,950:
> -- empty?
> -- empty?
> =#q == 0
> =#q == 0
true</lang>
true</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 1,956: Line 1,956:




<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckStackAsLIFO {
Module CheckStackAsLIFO {
a=stack
a=stack
Line 1,995: Line 1,995:
}
}
CheckStackAsFIFO
CheckStackAsFIFO
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
There are more builtin operations like reverse(), length(),etc.
There are more builtin operations like reverse(), length(),etc.
<lang Maple>q := queue[new]();
<syntaxhighlight lang="maple">q := queue[new]();
queue[enqueue](q,1);
queue[enqueue](q,1);
queue[enqueue](q,2);
queue[enqueue](q,2);
Line 2,012: Line 2,012:
>>>3
>>>3
queue[empty](q);
queue[empty](q);
>>>true</lang>
>>>true</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Empty[a_] := If[Length[a] == 0, True, False]
<syntaxhighlight lang="mathematica">Empty[a_] := If[Length[a] == 0, True, False]
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
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]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]
Line 2,030: Line 2,030:
->1
->1
Pop[Queue]
Pop[Queue]
->False</lang>
->False</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
The <tt>Nemerle.Collections</tt> namespace contains an implementation of a Queue.
The <tt>Nemerle.Collections</tt> namespace contains an implementation of a Queue.
<lang Nemerle>mutable q = Queue(); // or use immutable version as per Haskell example
<syntaxhighlight lang="nemerle">mutable q = Queue(); // or use immutable version as per Haskell example
def empty = q.IsEmpty(); // true at this point
def empty = q.IsEmpty(); // true at this point
q.Push(empty); // or Enqueue(), or Add()
q.Push(empty); // or Enqueue(), or Add()
def a = q.Pop(); // or Dequeue() or Take()</lang>
def a = q.Pop(); // or Dequeue() or Take()</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
Line 2,043: Line 2,043:


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.
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.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary


Line 2,108: Line 2,108:
method isFalse public constant binary returns boolean
method isFalse public constant binary returns boolean
return \isTrue
return \isTrue
</syntaxhighlight>
</lang>
;Output
;Output
<pre>
<pre>
Line 2,123: Line 2,123:
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.
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.


<lang nim>import deques
<syntaxhighlight lang="nim">import deques


var queue = initDeque[int]()
var queue = initDeque[int]()
Line 2,134: Line 2,134:
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()
echo "Popping: ", queue.popFirst()</lang>
echo "Popping: ", queue.popFirst()</syntaxhighlight>
{{out}}
{{out}}
<pre>Queue size: 3
<pre>Queue size: 3
Line 2,145: Line 2,145:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
class Test {
class Test {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 2,160: Line 2,160:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml># let q = Queue.create ();;
<syntaxhighlight lang="ocaml"># let q = Queue.create ();;
val q : '_a Queue.t = <abstr>
val q : '_a Queue.t = <abstr>
# Queue.is_empty q;;
# Queue.is_empty q;;
Line 2,199: Line 2,199:
- : int = 4
- : int = 4
# Queue.is_empty q;;
# Queue.is_empty q;;
- : bool = true</lang>
- : bool = true</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 2,205: Line 2,205:
Using FIFO implementation :
Using FIFO implementation :


<lang oforth>: testQueue
<syntaxhighlight lang="oforth">: testQueue
| q i |
| q i |
Queue new ->q
Queue new ->q
20 loop: i [ i q push ]
20 loop: i [ i q push ]
while ( q empty not ) [ q pop . ] ;</lang>
while ( q empty not ) [ q pop . ] ;</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
ooRexx includes a built-in queue class.
ooRexx includes a built-in queue class.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
q = .queue~new -- create an instance
q = .queue~new -- create an instance
q~queue(3) -- adds to the end, but this is at the front
q~queue(3) -- adds to the end, but this is at the front
Line 2,219: Line 2,219:
q~queue(2) -- add to the end
q~queue(2) -- add to the end
say q~pull q~pull q~pull q~isempty -- should display all and be empty
say q~pull q~pull q~pull q~isempty -- should display all and be empty
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 2,226: Line 2,226:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
[Queue] = {Link ['x-oz://system/adt/Queue.ozf']}
[Queue] = {Link ['x-oz://system/adt/Queue.ozf']}
MyQueue = {Queue.new}
MyQueue = {Queue.new}
Line 2,237: Line 2,237:
{Show {MyQueue.get}} %% foo
{Show {MyQueue.get}} %% foo
{Show {MyQueue.get}} %% bar
{Show {MyQueue.get}} %% bar
{Show {MyQueue.get}} %% baz</lang>
{Show {MyQueue.get}} %% baz</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
Perl has built-in support to these operations:
Perl has built-in support to these operations:
<lang perl>@queue = (); # we will simulate a queue in a array
<syntaxhighlight lang="perl">@queue = (); # we will simulate a queue in a array


push @queue, (1..5); # enqueue numbers from 1 to 5
push @queue, (1..5); # enqueue numbers from 1 to 5
Line 2,251: Line 2,251:
print $n while($n = shift @queue); # dequeue all
print $n while($n = shift @queue); # dequeue all
print "\n";
print "\n";
print "array is empty\n" unless @queue; # is empty ?</lang>
print "array is empty\n" unless @queue; # is empty ?</syntaxhighlight>
Output:
Output:
<lang>1
<syntaxhighlight lang="text">1
2345
2345
array is empty</lang>
array is empty</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Using the implementation from [[Queue/Definition#Phix|Queue/Definition]]
Using the implementation from [[Queue/Definition#Phix|Queue/Definition]]
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #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>
Line 2,268: Line 2,268:
<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;">"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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
Using the builtins (same output):
Using the builtins (same output):
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #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>
Line 2,280: Line 2,280:
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PHP}}==
=={{header|PHP}}==
{{works with|PHP|5.3+}}
{{works with|PHP|5.3+}}
<lang php><?php
<syntaxhighlight lang="php"><?php
$queue = new SplQueue;
$queue = new SplQueue;
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // empty test - returns true
Line 2,293: Line 2,293:
echo $queue->dequeue(), "\n"; // returns 1
echo $queue->dequeue(), "\n"; // returns 1
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // returns false
echo $queue->isEmpty() ? 'true' : 'false', "\n"; // returns false
?></lang>
?></syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Using the implementation from [[FIFO]]:
Using the implementation from [[FIFO]]:
<lang PicoLisp>(println (fifo 'Queue)) # Retrieve the number '1'
<syntaxhighlight lang="picolisp">(println (fifo 'Queue)) # Retrieve the number '1'
(println (fifo 'Queue)) # Retrieve an internal symbol 'abc'
(println (fifo 'Queue)) # Retrieve an internal symbol 'abc'
(println (fifo 'Queue)) # Retrieve a transient symbol "abc"
(println (fifo 'Queue)) # Retrieve a transient symbol "abc"
(println (fifo 'Queue)) # and a list (abc)
(println (fifo 'Queue)) # and a list (abc)
(println (fifo 'Queue)) # Queue is empty -> NIL</lang>
(println (fifo 'Queue)) # Queue is empty -> NIL</syntaxhighlight>
Output:
Output:
<pre>1
<pre>1
Line 2,310: Line 2,310:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
test: proc options (main);
test: proc options (main);


Line 2,351: Line 2,351:
end;
end;
end test;
end test;
</syntaxhighlight>
</lang>
The output:
The output:
<lang>
<syntaxhighlight lang="text">
1
1
3
3
Line 2,375: Line 2,375:
17
17
19
19
</syntaxhighlight>
</lang>


=={{header|PostScript}}==
=={{header|PostScript}}==
{{libheader|initlib}}
{{libheader|initlib}}
<lang postscript>
<syntaxhighlight lang="postscript">
[1 2 3 4 5] 6 exch tadd
[1 2 3 4 5] 6 exch tadd
= [1 2 3 4 5 6]
= [1 2 3 4 5 6]
Line 2,386: Line 2,386:
[] empty?
[] empty?
=true
=true
</syntaxhighlight>
</lang>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Line 2,392: Line 2,392:
{{works with|PowerShell|4.0}}
{{works with|PowerShell|4.0}}


<syntaxhighlight lang="powershell">
<lang PowerShell>
[System.Collections.ArrayList]$queue = @()
[System.Collections.ArrayList]$queue = @()
# isEmpty?
# isEmpty?
Line 2,419: Line 2,419:
}
}
"the queue contains : $queue"
"the queue contains : $queue"
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 2,435: Line 2,435:
===PowerShell using the .NET Queue Class===
===PowerShell using the .NET Queue Class===
Declare a new queue:
Declare a new queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue = New-Object -TypeName System.Collections.Queue
$queue = New-Object -TypeName System.Collections.Queue
#or
#or
$queue = [System.Collections.Queue] @()
$queue = [System.Collections.Queue] @()
</syntaxhighlight>
</lang>
Show the methods and properties of the queue object:
Show the methods and properties of the queue object:
<syntaxhighlight lang="powershell">
<lang PowerShell>
Get-Member -InputObject $queue
Get-Member -InputObject $queue
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,469: Line 2,469:
</pre>
</pre>
Put some stuff in the queue:
Put some stuff in the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
1,2,3 | ForEach-Object {$queue.Enqueue($_)}
1,2,3 | ForEach-Object {$queue.Enqueue($_)}
</syntaxhighlight>
</lang>
Take a peek at the head of the queue:
Take a peek at the head of the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Peek()
$queue.Peek()
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,481: Line 2,481:
</pre>
</pre>
Pop the head of the queue:
Pop the head of the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Dequeue()
$queue.Dequeue()
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,489: Line 2,489:
</pre>
</pre>
Clear the queue:
Clear the queue:
<syntaxhighlight lang="powershell">
<lang PowerShell>
$queue.Clear()
$queue.Clear()
</syntaxhighlight>
</lang>
Test if queue is empty:
Test if queue is empty:
<syntaxhighlight lang="powershell">
<lang PowerShell>
if (-not $queue.Count) {"Queue is empty"}
if (-not $queue.Count) {"Queue is empty"}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,504: Line 2,504:
Works with SWI-Prolog.
Works with SWI-Prolog.


<lang Prolog>%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
<syntaxhighlight lang="prolog">%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% definitions of queue
%% definitions of queue
empty(U-V) :-
empty(U-V) :-
Line 2,552: Line 2,552:
write('Pop the queue : '),
write('Pop the queue : '),
pop(Q4, _V, _Q5).
pop(Q4, _V, _Q5).
</syntaxhighlight>
</lang>
Output :
Output :
<pre>?- queue.
<pre>?- queue.
Line 2,570: Line 2,570:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>NewList MyStack()
<syntaxhighlight lang="purebasic">NewList MyStack()


Procedure Push(n)
Procedure Push(n)
Line 2,606: Line 2,606:
Debug Pop()
Debug Pop()
Wend
Wend
</syntaxhighlight>
</lang>


'''Outputs
'''Outputs
Line 2,616: Line 2,616:


=={{header|Python}}==
=={{header|Python}}==
<lang python>import Queue
<syntaxhighlight lang="python">import Queue
my_queue = Queue.Queue()
my_queue = Queue.Queue()
my_queue.put("foo")
my_queue.put("foo")
Line 2,623: Line 2,623:
print my_queue.get() # foo
print my_queue.get() # foo
print my_queue.get() # bar
print my_queue.get() # bar
print my_queue.get() # baz</lang>
print my_queue.get() # baz</syntaxhighlight>


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang Quackery>[ [] ] is queue ( --> q )
<syntaxhighlight lang="quackery">[ [] ] is queue ( --> q )


[ nested join ] is push ( q x --> q )
[ nested join ] is push ( q x --> q )
Line 2,632: Line 2,632:
[ behead ] is pop ( q --> q x )
[ behead ] is pop ( q --> q x )


[ [] = ] is empty? ( q --> b )</lang>
[ [] = ] is empty? ( q --> b )</syntaxhighlight>
'''Demonstrating operations in Quackery shell:'''
'''Demonstrating operations in Quackery shell:'''
<pre>/O> queue
<pre>/O> queue
Line 2,654: Line 2,654:


=={{header|Racket}}==
=={{header|Racket}}==
<lang Racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(require data/queue)
(require data/queue)
Line 2,670: Line 2,670:
(dequeue! queue) ; 'green
(dequeue! queue) ; 'green


(queue-empty? queue) ; #t</lang>
(queue-empty? queue) ; #t</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
Line 2,676: Line 2,676:


Raku maintains the same list operators of Perl 5, for this task, the operations are:
Raku maintains the same list operators of Perl 5, for this task, the operations are:
<lang>push (aka enqueue) -- @list.push
<syntaxhighlight lang="text">push (aka enqueue) -- @list.push
pop (aka dequeue) -- @list.shift
pop (aka dequeue) -- @list.shift
empty -- !@list.elems</lang>
empty -- !@list.elems</syntaxhighlight>
but there's also @list.pop which removes a item from the end,
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/>
and @list.unshift which add a item on the start of the list.<br/>
Example:
Example:
<lang perl6>my @queue = < a >;
<syntaxhighlight lang="raku" line>my @queue = < a >;


@queue.push('b', 'c'); # [ a, b, c ]
@queue.push('b', 'c'); # [ a, b, c ]
Line 2,693: Line 2,693:


@queue.unshift('A'); # [ A, b ]
@queue.unshift('A'); # [ A, b ]
@queue.push('C'); # [ A, b, C ]</lang>
@queue.push('C'); # [ A, b, C ]</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
Line 2,699: Line 2,699:
See [[FIFO#REBOL]] for implementation. Example repeated here for completeness.
See [[FIFO#REBOL]] for implementation. Example repeated here for completeness.


<lang REBOL>; Create and populate a FIFO:
<syntaxhighlight lang="rebol">; Create and populate a FIFO:


q: make fifo []
q: make fifo []
Line 2,713: Line 2,713:
while [not q/empty][print [" " q/pop]]
while [not q/empty][print [" " q/pop]]
print rejoin ["Queue is " either q/empty [""]["not "] "empty."]
print rejoin ["Queue is " either q/empty [""]["not "] "empty."]
print ["Trying to pop an empty queue yields:" q/pop]</lang>
print ["Trying to pop an empty queue yields:" q/pop]</syntaxhighlight>


Output:
Output:
Line 2,742: Line 2,742:


The entries in the stack may be anything, including "nulls".
The entries in the stack may be anything, including "nulls".
<lang rexx>/*REXX program demonstrates four queueing operations: push, pop, empty, query. */
<syntaxhighlight lang="rexx">/*REXX program demonstrates four queueing operations: push, pop, empty, query. */
say '══════════════════════════════════ Pushing five values to the stack.'
say '══════════════════════════════════ Pushing five values to the stack.'
do j=1 for 4 /*a DO loop to PUSH four values. */
do j=1 for 4 /*a DO loop to PUSH four values. */
Line 2,763: Line 2,763:
push: queue arg(1); return /*(The REXX QUEUE is FIFO.) */
push: queue arg(1); return /*(The REXX QUEUE is FIFO.) */
pop: procedure; parse pull x; return x /*REXX PULL removes a stack item. */
pop: procedure; parse pull x; return x /*REXX PULL removes a stack item. */
empty: return queued()==0 /*returns the status of the stack. */</lang>
empty: return queued()==0 /*returns the status of the stack. */</syntaxhighlight>
{{out|output|text=:}}
{{out|output|text=:}}
<pre>
<pre>
Line 2,787: Line 2,787:


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>use std::collections::VecDeque;
<syntaxhighlight lang="rust">use std::collections::VecDeque;


fn main() {
fn main() {
Line 2,801: Line 2,801:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>val q=scala.collection.mutable.Queue[Int]()
<syntaxhighlight lang="scala">val q=scala.collection.mutable.Queue[Int]()
println("isEmpty = " + q.isEmpty)
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
Line 2,814: Line 2,814:
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)</lang>
println("isEmpty = " + q.isEmpty)</syntaxhighlight>
Output:
Output:
<pre>isEmpty = true
<pre>isEmpty = true
Line 2,826: Line 2,826:
=={{header|Sidef}}==
=={{header|Sidef}}==
Using the class defined at [[FIFO#Sidef]]
Using the class defined at [[FIFO#Sidef]]
<lang ruby>var f = FIFO();
<syntaxhighlight lang="ruby">var f = FIFO();
say f.empty; # true
say f.empty; # true
f.push('foo');
f.push('foo');
Line 2,835: Line 2,835:
var g = FIFO('xxx', 'yyy');
var g = FIFO('xxx', 'yyy');
say g.pop; # xxx
say g.pop; # xxx
say f.pop; # bar</lang>
say f.pop; # bar</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
{{works with|SML/NJ}}
{{works with|SML/NJ}}
; Functional interface
; Functional interface
<lang sml>- open Fifo;
<syntaxhighlight lang="sml">- open Fifo;
opening Fifo
opening Fifo
datatype 'a fifo = ...
datatype 'a fifo = ...
Line 2,887: Line 2,887:
val v''' = 4 : int
val v''' = 4 : int
- isEmpty q'''''';
- isEmpty q'''''';
val it = true : bool</lang>
val it = true : bool</syntaxhighlight>


{{works with|SML/NJ}}
{{works with|SML/NJ}}
; Imperative interface
; Imperative interface
<lang sml>- open Queue;
<syntaxhighlight lang="sml">- open Queue;
opening Queue
opening Queue
type 'a queue
type 'a queue
Line 2,945: Line 2,945:
val it = 4 : int
val it = 4 : int
- isEmpty q;
- isEmpty q;
val it = true : bool</lang>
val it = true : bool</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 2,952: Line 2,952:
=={{header|Tcl}}==
=={{header|Tcl}}==
See [[FIFO#Tcl|FIFO]] for operation implementations:
See [[FIFO#Tcl|FIFO]] for operation implementations:
<lang tcl>set Q [list]
<syntaxhighlight lang="tcl">set Q [list]
empty Q ;# ==> 1 (true)
empty Q ;# ==> 1 (true)
push Q foo
push Q foo
Line 2,959: Line 2,959:
peek Q ;# ==> foo
peek Q ;# ==> foo
pop Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar</lang>
peek Q ;# ==> bar</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|ksh93}}
{{works with|ksh93}}
See [[Queue/Definition#UNIX_Shell|Queue/Definition]] for implementation:
See [[Queue/Definition#UNIX_Shell|Queue/Definition]] for implementation:
<lang bash># any valid variable name can be used as a queue without initialization
<syntaxhighlight 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
queue_empty foo && echo foo is empty || echo foo is not empty
Line 2,977: Line 2,977:
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo
print "peek: $(queue_peek foo)"; queue_pop foo</lang>
print "peek: $(queue_peek foo)"; queue_pop foo</syntaxhighlight>


Output:
Output:
Line 2,991: Line 2,991:
See [[Queue/Definition#VBA]] for implementation.
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.
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.
<lang vb>Public Sub fifo()
<syntaxhighlight lang="vb">Public Sub fifo()
push "One"
push "One"
push "Two"
push "Two"
push "Three"
push "Three"
Debug.Print pop, pop, pop, empty_
Debug.Print pop, pop, pop, empty_
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>One Two Three True</pre>
<pre>One Two Three True</pre>


Line 3,016: Line 3,016:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-queue}}
{{libheader|Wren-queue}}
<lang ecmascript>import "/queue" for Queue
<syntaxhighlight lang="ecmascript">import "/queue" for Queue


var q = Queue.new()
var q = Queue.new()
Line 3,028: Line 3,028:
q.clear()
q.clear()
System.print("Queue cleared")
System.print("Queue cleared")
System.print("Is queue now empty? %((q.isEmpty) ? "yes" : "no")")</lang>
System.print("Is queue now empty? %((q.isEmpty) ? "yes" : "no")")</syntaxhighlight>


{{out}}
{{out}}
Line 3,041: Line 3,041:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
def Size=8;
def Size=8;
int Fifo(Size);
int Fifo(Size);
Line 3,088: Line 3,088:
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
]</lang>
]</syntaxhighlight>


Output:
Output:
Line 3,105: Line 3,105:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>sub push(x$)
<syntaxhighlight lang="yabasic">sub push(x$)
queue$ = queue$ + x$ + "#"
queue$ = queue$ + x$ + "#"
end sub
end sub
Line 3,145: Line 3,145:
wend
wend


print "Pop ", pop$()</lang>
print "Pop ", pop$()</syntaxhighlight>


{{out}}
{{out}}