tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,13 @@
{{Data structure}}
[[File:Fifo.gif|frame|right|Illustration of FIFO behavior]]
Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion.
Operations:
* push (aka ''enqueue'') - add element
* pop (aka ''dequeue'') - pop first element
* empty - return truth value when empty
Errors:
* handle the error of trying to pop from an empty queue (behavior depends on the language and platform)
See [[Queue/Usage]] for the built-in FIFO or queue of your language or standard library.

View file

@ -0,0 +1,2 @@
---
note: Data Structures

View file

@ -0,0 +1,14 @@
(defun enqueue (x xs)
(cons x xs))
(defun dequeue (xs)
(declare (xargs :guard (and (consp xs)
(true-listp xs))))
(if (or (endp xs) (endp (rest xs)))
(mv (first xs) nil)
(mv-let (x ys)
(dequeue (rest xs))
(mv x (cons (first xs) ys)))))
(defun empty (xs)
(endp xs))

View file

@ -0,0 +1,32 @@
#!/usr/bin/awk -f
BEGIN {
delete q
print "empty? " emptyP()
print "push " push("a")
print "push " push("b")
print "empty? " emptyP()
print "pop " pop()
print "pop " pop()
print "empty? " emptyP()
print "pop " pop()
}
function push(n) {
q[length(q)+1] = n
return n
}
function pop() {
if (emptyP()) {
print "Popping from empty queue."
exit
}
r = q[length(q)]
delete q[length(q)]
return r
}
function emptyP() {
return length(q) == 0
}

View file

@ -0,0 +1,20 @@
generic
type Element_Type is private;
package Fifo is
type Fifo_Type is private;
procedure Push(List : in out Fifo_Type; Item : in Element_Type);
procedure Pop(List : in out Fifo_Type; Item : out Element_Type);
function Is_Empty(List : Fifo_Type) return Boolean;
Empty_Error : exception;
private
type Fifo_Element;
type Fifo_Ptr is access Fifo_Element;
type Fifo_Type is record
Head : Fifo_Ptr := null;
Tail : Fifo_Ptr := null;
end record;
type Fifo_Element is record
Value : Element_Type;
Next : Fifo_Ptr := null;
end record;
end Fifo;

View file

@ -0,0 +1,11 @@
generic
type Element_Type is private;
package Asynchronous_Fifo is
protected type Fifo is
procedure Push(Item : Element_Type);
entry Pop(Item : out Element_Type);
private
Value : Element_Type;
Valid : Boolean := False;
end Fifo;
end Asynchronous_Fifo;

View file

@ -0,0 +1,30 @@
package body Asynchronous_Fifo is
----------
-- Fifo --
----------
protected body Fifo is
----------
-- Push --
----------
procedure Push (Item : Element_Type) is
begin
Value := Item;
Valid := True;
end Push;
---------
-- Pop --
---------
entry Pop (Item : out Element_Type) when Valid is
begin
Item := Value;
end Pop;
end Fifo;
end Asynchronous_Fifo;

View file

@ -0,0 +1,48 @@
with Asynchronous_Fifo;
with Ada.Text_Io; use Ada.Text_Io;
procedure Asynchronous_Fifo_Test is
package Int_Fifo is new Asynchronous_Fifo(Integer);
use Int_Fifo;
Buffer : Fifo;
task Writer is
entry Stop;
end Writer;
task body Writer is
Val : Positive := 1;
begin
loop
select
accept Stop;
exit;
else
Buffer.Push(Val);
Val := Val + 1;
end select;
end loop;
end Writer;
task Reader is
entry Stop;
end Reader;
task body Reader is
Val : Positive;
begin
loop
select
accept Stop;
exit;
else
Buffer.Pop(Val);
Put_Line(Integer'Image(Val));
end select;
end loop;
end Reader;
begin
delay 0.1;
Writer.Stop;
Reader.Stop;
end Asynchronous_Fifo_Test;

View file

@ -0,0 +1,49 @@
with Ada.Unchecked_Deallocation;
package body Fifo is
----------
-- Push --
----------
procedure Push (List : in out Fifo_Type; Item : in Element_Type) is
Temp : Fifo_Ptr := new Fifo_Element'(Item, null);
begin
if List.Tail = null then
List.Tail := Temp;
end if;
if List.Head /= null then
List.Head.Next := Temp;
end if;
List.Head := Temp;
end Push;
---------
-- Pop --
---------
procedure Pop (List : in out Fifo_Type; Item : out Element_Type) is
procedure Free is new Ada.Unchecked_Deallocation(Fifo_Element, Fifo_Ptr);
Temp : Fifo_Ptr := List.Tail;
begin
if List.Head = null then
raise Empty_Error;
end if;
Item := List.Tail.Value;
List.Tail := List.Tail.Next;
if List.Tail = null then
List.Head := null;
end if;
Free(Temp);
end Pop;
--------------
-- Is_Empty --
--------------
function Is_Empty (List : Fifo_Type) return Boolean is
begin
return List.Head = null;
end Is_Empty;
end Fifo;

View file

@ -0,0 +1,17 @@
with Fifo;
with Ada.Text_Io; use Ada.Text_Io;
procedure Fifo_Test is
package Int_Fifo is new Fifo(Integer);
use Int_Fifo;
My_Fifo : Fifo_Type;
Val : Integer;
begin
for I in 1..10 loop
Push(My_Fifo, I);
end loop;
while not Is_Empty(My_Fifo) loop
Pop(My_Fifo, Val);
Put_Line(Integer'Image(Val));
end loop;
end Fifo_Test;

View file

@ -0,0 +1,13 @@
with Ada.Containers.Doubly_Linked_Lists;
generic
type Element_Type is private;
package Generic_Fifo is
type Fifo_Type is tagged private;
procedure Push(The_Fifo : in out Fifo_Type; Item : in Element_Type);
procedure Pop(The_Fifo : in out Fifo_Type; Item : out Element_Type);
Empty_Error : Exception;
private
package List_Pkg is new Ada.Containers.Doubly_Linked_Lists(Element_Type);
use List_Pkg;
Type Fifo_Type is new List with null record;
end Generic_Fifo;

View file

@ -0,0 +1,25 @@
package body Generic_Fifo is
----------
-- Push --
----------
procedure Push (The_Fifo : in out Fifo_Type; Item : in Element_Type) is
begin
The_Fifo.Prepend(Item);
end Push;
---------
-- Pop --
---------
procedure Pop (The_Fifo : in out Fifo_Type; Item : out Element_Type) is
begin
if Is_Empty(The_Fifo) then
raise Empty_Error;
end if;
Item := The_Fifo.Last_Element;
The_Fifo.Delete_Last;
end Pop;
end Generic_Fifo;

View file

@ -0,0 +1,17 @@
with Generic_Fifo;
with Ada.Text_Io; use Ada.Text_Io;
procedure Generic_Fifo_Test is
package Int_Fifo is new Generic_Fifo(Integer);
use Int_Fifo;
My_Fifo : Fifo_Type;
Val : Integer;
begin
for I in 1..10 loop
My_Fifo.Push(I);
end loop;
while not My_Fifo.Is_Empty loop
My_Fifo.Pop(Val);
Put_Line(Integer'Image(Val));
end loop;
end Generic_Fifo_Test;

View file

@ -0,0 +1,11 @@
generic
type Element_Type is private;
package Synchronous_Fifo is
protected type Fifo is
entry Push(Item : Element_Type);
entry Pop(Item : out Element_Type);
private
Value : Element_Type;
Is_New : Boolean := False;
end Fifo;
end Synchronous_Fifo;

View file

@ -0,0 +1,31 @@
package body Synchronous_Fifo is
----------
-- Fifo --
----------
protected body Fifo is
---------
-- Push --
---------
entry Push (Item : Element_Type) when not Is_New is
begin
Value := Item;
Is_New := True;
end Push;
---------
-- Pop --
---------
entry Pop (Item : out Element_Type) when Is_New is
begin
Item := Value;
Is_New := False;
end Pop;
end Fifo;
end Synchronous_Fifo;

View file

@ -0,0 +1,56 @@
with Synchronous_Fifo;
with Ada.Text_Io; use Ada.Text_Io;
procedure Synchronous_Fifo_Test is
package Int_Fifo is new Synchronous_Fifo(Integer);
use Int_Fifo;
Buffer : Fifo;
task Writer is
entry Stop;
end Writer;
task body Writer is
Val : Positive := 1;
begin
loop
select
accept Stop;
exit;
else
select
Buffer.Push(Val);
Val := Val + 1;
or
delay 1.0;
end select;
end select;
end loop;
end Writer;
task Reader is
entry Stop;
end Reader;
task body Reader is
Val : Positive;
begin
loop
select
accept Stop;
exit;
else
select
Buffer.Pop(Val);
Put_Line(Integer'Image(Val));
or
delay 1.0;
end select;
end select;
end loop;
end Reader;
begin
delay 0.1;
Writer.Stop;
Reader.Stop;
end Synchronous_Fifo_Test;

View file

@ -0,0 +1,31 @@
push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST
MsgBox % "Len = " len("qu") ; Number of entries
While !empty("qu") ; Repeat until queue is not empty
MsgBox % pop("qu") ; Print popped values (2, 44, xyz)
MsgBox Error = %ErrorLevel% ; ErrorLevel = 0: OK
MsgBox % pop("qu") ; Empty
MsgBox Error = %ErrorLevel% ; ErrorLevel = -1: popped too much
MsgBox % "Len = " len("qu") ; Number of entries
push(queue,_) { ; push _ onto queue named "queue" (!=_), _ string not containing |
Global
%queue% .= %queue% = "" ? _ : "|" _
}
pop(queue) { ; pop value from queue named "queue" (!=_,_1,_2)
Global
RegExMatch(%queue%, "([^\|]*)\|?(.*)", _)
Return _1, ErrorLevel := -(%queue%=""), %queue% := _2
}
empty(queue) { ; check if queue named "queue" is empty
Global
Return %queue% = ""
}
len(queue) { ; number of entries in "queue"
Global
StringReplace %queue%, %queue%, |, |, UseErrorLevel
Return %queue% = "" ? 0 : ErrorLevel+1
}

View file

@ -0,0 +1,31 @@
FIFOSIZE = 1000
FOR n = 3 TO 5
PRINT "Push ";n : PROCenqueue(n)
NEXT
PRINT "Pop " ; FNdequeue
PRINT "Push 6" : PROCenqueue(6)
REPEAT
PRINT "Pop " ; FNdequeue
UNTIL FNisempty
PRINT "Pop " ; FNdequeue
END
DEF PROCenqueue(n) : LOCAL f%
DEF FNdequeue : LOCAL f% : f% = 1
DEF FNisempty : LOCAL f% : f% = 2
PRIVATE fifo(), rptr%, wptr%
DIM fifo(FIFOSIZE-1)
CASE f% OF
WHEN 0:
wptr% = (wptr% + 1) MOD FIFOSIZE
IF rptr% = wptr% ERROR 100, "Error: queue overflowed"
fifo(wptr%) = n
WHEN 1:
IF rptr% = wptr% ERROR 101, "Error: queue empty"
rptr% = (rptr% + 1) MOD FIFOSIZE
= fifo(rptr%)
WHEN 2:
= (rptr% = wptr%)
ENDCASE
ENDPROC

View file

@ -0,0 +1,69 @@
@echo off
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: FIFO queue usage
:: Define the queue
call :newQueue myQ
:: Populate the queue
for %%A in (value1 value2 value3) do call :enqueue myQ %%A
:: Test if queue is empty by examining the tail "attribute"
if myQ.tail==0 (echo myQ is empty) else (echo myQ is NOT empty)
:: Peek at the head of the queue
call:peekQueue myQ val && echo a peek at the head of myQueue shows !val!
:: Process the first queue value
call :dequeue myQ val && echo dequeued myQ value=!val!
:: Add some more values to the queue
for %%A in (value4 value5 value6) do call :enqueue myQ %%A
:: Process the remainder of the queue
:processQueue
call :dequeue myQ val || goto :queueEmpty
echo dequeued myQ value=!val!
goto :processQueue
:queueEmpty
:: Test if queue is empty using the empty "method"/"macro". Use of the
:: second IF statement serves to demonstrate the negation of the empty
:: "method". A single IF could have been used with an ELSE clause instead.
if %myQ.empty% echo myQ is empty
if not %myQ.empty% echo myQ is NOT empty
exit /b
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: FIFO queue definition
:newQueue qName
set /a %~1.head=1, %~1.tail=0
:: Define an empty "method" for this queue as a sort of macro
set "%~1.empty=^!%~1.tail^! == 0"
exit /b
:enqueue qName value
set /a %~1.tail+=1
set %~1.!%~1.tail!=%2
exit /b
:dequeue qName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because queue was empty
if !%~1.tail! equ 0 exit /b 1
for %%N in (!%~1.head!) do (
set %~2=!%~1.%%N!
set %~1.%%N=
)
if !%~1.head! == !%~1.tail! (set /a "%~1.head=1, %~1.tail=0") else set /a %~1.head+=1
exit /b 0
:peekQueue qName returnVar
:: Sets errorlevel to 0 if success
:: Sets errorlevel to 1 if failure because queue was empty
if !%~1.tail! equ 0 exit /b 1
for %%N in (!%~1.head!) do set %~2=!%~1.%%N!
exit /b 0

View file

@ -0,0 +1,67 @@
namespace rosettacode
{
template<typename T> class queue
{
public:
queue();
~queue();
void push(T const& t);
T pop();
bool empty();
private:
void drop();
struct node;
node* head;
node* tail;
};
template<typename T> struct queue<T>::node
{
T data;
node* next;
node(T const& t): data(t), next(0) {}
};
template<typename T>
queue<T>::queue():
head(0)
{
}
template<typename T>
inline void queue<T>::drop()
{
node* n = head;
head = head->next;
delete n;
}
template<typename T>
queue<T>::~queue()
{
while (!empty())
drop();
}
template<typename T>
void queue<T>::push(T const& t)
{
node*& next = head? tail->next : head;
next = new node(t);
tail = next;
}
template<typename T>
T queue<T>::pop()
{
T tmp = head->data;
drop();
return tmp;
}
template<typename T>
bool queue<T>::empty()
{
return head == 0;
}
}

View file

@ -0,0 +1,38 @@
public class FIFO<T>
{
class Node
{
public T Item { get; set; }
public Node Next { get; set; }
}
Node first = null;
Node last = null;
public void push(T item)
{
if (empty())
{
//Uses object initializers to set fields of new node
first = new Node() { Item = item, Next = null };
last = first;
}
else
{
last.Next = new Node() { Item = item, Next = null };
last = last.Next;
}
}
public T pop()
{
if (first == null)
throw new System.Exception("No elements");
if (last == first)
last = null;
T temp = first.Item;
first = first.Next;
return temp;
}
public bool empty()
{
return first == null;
}
}

View file

@ -0,0 +1,50 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int DATA; /* type of data to store in queue */
typedef struct {
DATA *buf;
size_t head, tail, alloc;
} queue_t, *queue;
queue q_new()
{
queue q = malloc(sizeof(queue_t));
q->buf = malloc(sizeof(DATA) * (q->alloc = 4));
q->head = q->tail = 0;
return q;
}
int empty(queue q)
{
return q->tail == q->head;
}
void enqueue(queue q, DATA n)
{
if (q->tail >= q->alloc) q->tail = 0;
q->buf[q->tail++] = n;
if (q->tail == q->head) { /* needs more room */
q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2);
if (q->head) {
memcpy(q->buf + q->head + q->alloc, q->buf + q->head,
sizeof(DATA) * (q->alloc - q->head));
q->head += q->alloc;
} else
q->tail = q->alloc;
q->alloc *= 2;
}
}
int dequeue(queue q, DATA *n)
{
if (q->head == q->tail) return 0;
*n = q->buf[q->head++];
if (q->head >= q->alloc) { /* reduce allocated storage no longer needed */
q->head = 0;
if (q->alloc >= 512 && q->tail < q->alloc / 2)
q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2));
}
return 1;
}

View file

@ -0,0 +1,43 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct node_t node_t, *node, *queue;
struct node_t { int val; node prev, next; };
#define HEAD(q) q->prev
#define TAIL(q) q->next
queue q_new()
{
node q = malloc(sizeof(node_t));
q->next = q->prev = 0;
return q;
}
int empty(queue q)
{
return !HEAD(q);
}
void enqueue(queue q, int n)
{
node nd = malloc(sizeof(node_t));
nd->val = n;
if (!HEAD(q)) HEAD(q) = nd;
nd->prev = TAIL(q);
if (nd->prev) nd->prev->next = nd;
TAIL(q) = nd;
nd->next = 0;
}
int dequeue(queue q, int *val)
{
node tmp = HEAD(q);
if (!tmp) return 0;
*val = tmp->val;
HEAD(q) = tmp->next;
if (TAIL(q) == tmp) TAIL(q) = 0;
free(tmp);
return 1;
}

View file

@ -0,0 +1,22 @@
int main()
{
int i, n;
queue q = q_new();
for (i = 0; i < 100000000; i++) {
n = rand();
if (n > RAND_MAX / 2) {
// printf("+ %d\n", n);
enqueue(q, n);
} else {
if (!dequeue(q, &n)) {
// printf("empty\n");
continue;
}
// printf("- %d\n", n);
}
}
while (dequeue(q, &n));// printf("- %d\n", n);
return 0;
}

View file

@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/queue.h>
struct entry {
int value;
TAILQ_ENTRY(entry) entries;
};
typedef struct entry entry_t;
TAILQ_HEAD(FIFOList_s, entry);
typedef struct FIFOList_s FIFOList;
bool m_enqueue(int v, FIFOList *l)
{
entry_t *val;
val = malloc(sizeof(entry_t));
if ( val != NULL ) {
val->value = v;
TAILQ_INSERT_TAIL(l, val, entries);
return true;
}
return false;
}
bool m_dequeue(int *v, FIFOList *l)
{
entry_t *e = l->tqh_first;
if ( e != NULL ) {
*v = e->value;
TAILQ_REMOVE(l, e, entries);
free(e);
return true;
}
return false;
}
bool isQueueEmpty(FIFOList *l)
{
if ( l->tqh_first == NULL ) return true;
return false;
}

View file

@ -0,0 +1,15 @@
(defn make-queue []
(atom []))
(defn enqueue [q x]
(swap! q conj x))
(defn dequeue [q]
(if (seq @q)
(let [x (first @q)]
(swap! q subvec 1)
x)
(throw (IllegalStateException. "Can't pop an empty queue."))))
(defn queue-empty? [q]
(empty? @q))

View file

@ -0,0 +1,38 @@
# Implement a fifo as an array of arrays, to
# greatly amortize dequeue costs, at some expense of
# memory overhead and insertion time. The speedup
# depends on the underlying JS implementation, but
# it's significant on node.js.
Fifo = ->
max_chunk = 512
arr = [] # array of arrays
count = 0
self =
enqueue: (elem) ->
if count == 0 or arr[arr.length-1].length >= max_chunk
arr.push []
count += 1
arr[arr.length-1].push elem
dequeue: (elem) ->
throw Error("queue is empty") if count == 0
val = arr[0].shift()
count -= 1
if arr[0].length == 0
arr.shift()
val
is_empty: (elem) ->
count == 0
# test
do ->
max = 5000000
q = Fifo()
for i in [1..max]
q.enqueue
number: i
console.log q.dequeue()
while !q.is_empty()
v = q.dequeue()
console.log v

View file

@ -0,0 +1,7 @@
> time coffee fifo.coffee
{ number: 1 }
{ number: 5000000 }
real 0m2.394s
user 0m2.089s
sys 0m0.265s

View file

@ -0,0 +1,26 @@
(defstruct (queue (:constructor %make-queue))
(items '() :type list)
(tail '() :type list))
(defun make-queue ()
"Returns an empty queue."
(%make-queue))
(defun queue-empty-p (queue)
"Returns true if the queue is empty."
(endp (queue-items queue)))
(defun enqueue (item queue)
"Enqueue item in queue. Returns the queue."
(prog1 queue
(if (queue-empty-p queue)
(setf (queue-items queue) (list item)
(queue-tail queue) (queue-items queue))
(setf (cdr (queue-tail queue)) (list item)
(queue-tail queue) (cdr (queue-tail queue))))))
(defun dequeue (queue)
"Dequeues an item from queue. Signals an error if queue is empty."
(if (queue-empty-p queue)
(error "Cannot dequeue from empty queue.")
(pop (queue-items queue))))

View file

@ -0,0 +1,27 @@
def makeQueue() {
def [var head, var tail] := Ref.promise()
def writer {
to enqueue(value) {
def [nh, nt] := Ref.promise()
tail.resolve([value, nh])
tail := nt
}
}
def reader {
to empty() { return !Ref.isResolved(head) }
to dequeue(whenEmpty) {
if (Ref.isResolved(head)) {
def [value, next] := head
head := next
return value
} else {
throw.eject(whenEmpty, "pop() of empty queue")
}
}
}
return [reader, writer]
}

View file

@ -0,0 +1,23 @@
component GenericQueue ( Queue, Element );
type Queue;
Queue (MaxLength = integer) -> Queue;
Length( Queue ) -> integer;
Empty ( Queue ) -> boolean;
Full ( Queue ) -> boolean;
Push ( Queue, Element) -> nothing;
Pull ( Queue ) -> Element;
begin
Queue (MaxLength) = Queue:[ MaxLength; length:=0; list=alist(Element) ];
Length ( queue ) = queue.length;
Empty ( queue ) = (queue.length <= 0);
Full ( queue ) = (queue.length >= queue.MaxLength);
Push ( queue, element ) =
[ exception (Full(queue), "Queue Overflow");
queue.length:= queue.length + 1;
add (queue.list, element)];
Pull ( queue ) =
[ exception (Empty(queue), "Queue Underflow");
queue.length:= queue.length - 1;
remove(first(queue.list))];
end component GenericQueue;

View file

@ -0,0 +1,29 @@
use GenericQueue (QueueofPersons, Person);
type Person = text;
Q = QueueofPersons(25);
Push (Q, "Peter");
Push (Q, "Alice");
Push (Q, "Edward");
Q?
QueueofPersons:[MaxLength = 25;
length = 3;
list = { "Peter",
"Alice",
"Edward"}]
Pull (Q)?
"Peter"
Pull (Q)?
"Alice"
Pull (Q)?
"Edward"
Q?
QueueofPersons:[MaxLength = 25;
length = 0;
list = { }]
Pull (Q)?
***** Exception: Queue Underflow

View file

@ -0,0 +1,13 @@
-module(fifo).
-export([new/0, push/2, pop/1, empty/1]).
new() -> {fifo, [], []}.
push({fifo, In, Out}, X) -> {fifo, [X|In], Out}.
pop({fifo, [], []}) -> erlang:error('empty fifo');
pop({fifo, In, []}) -> pop({fifo, [], lists:reverse(In)});
pop({fifo, In, [H|T]}) -> {H, {fifo, In, T}}.
empty({fifo, [], []}) -> true;
empty({fifo, _, _}) -> false.

View file

@ -0,0 +1,24 @@
class Queue
{
List queue := [,]
public Void push (Obj obj)
{
queue.add (obj) // add to right of list
}
public Obj pop ()
{
if (queue.isEmpty)
throw (Err("queue is empty"))
else
{
return queue.removeAt(0) // removes left-most item
}
}
public Bool isEmpty ()
{
queue.isEmpty
}
}

View file

@ -0,0 +1,22 @@
1024 constant size
create buffer size cells allot
here constant end
variable head buffer head !
variable tail buffer tail !
variable used 0 used !
: empty? used @ 0= ;
: full? used @ size = ;
: next ( ptr -- ptr )
cell+ dup end = if drop buffer then ;
: put ( n -- )
full? abort" buffer full"
\ begin full? while pause repeat
tail @ ! tail @ next tail ! 1 used +! ;
: get ( -- n )
empty? abort" buffer empty"
\ begin empty? while pause repeat
head @ @ head @ next head ! -1 used +! ;

View file

@ -0,0 +1,69 @@
module FIFO
use fifo_nodes
! fifo_nodes must define the type fifo_node, with the two field
! next and valid, for queue handling, while the field datum depends
! on the usage (see [[FIFO (usage)]] for an example)
! type fifo_node
! integer :: datum
! ! the next part is not variable and must be present
! type(fifo_node), pointer :: next
! logical :: valid
! end type fifo_node
type fifo_head
type(fifo_node), pointer :: head, tail
end type fifo_head
contains
subroutine new_fifo(h)
type(fifo_head), intent(out) :: h
nullify(h%head)
nullify(h%tail)
end subroutine new_fifo
subroutine fifo_enqueue(h, n)
type(fifo_head), intent(inout) :: h
type(fifo_node), intent(inout), target :: n
if ( associated(h%tail) ) then
h%tail%next => n
h%tail => n
else
h%tail => n
h%head => n
end if
nullify(n%next)
end subroutine fifo_enqueue
subroutine fifo_dequeue(h, n)
type(fifo_head), intent(inout) :: h
type(fifo_node), intent(out), target :: n
if ( associated(h%head) ) then
n = h%head
if ( associated(n%next) ) then
h%head => n%next
else
nullify(h%head)
nullify(h%tail)
end if
n%valid = .true.
else
n%valid = .false.
end if
nullify(n%next)
end subroutine fifo_dequeue
function fifo_isempty(h) result(r)
logical :: r
type(fifo_head), intent(in) :: h
if ( associated(h%head) ) then
r = .false.
else
r = .true.
end if
end function fifo_isempty
end module FIFO

View file

@ -0,0 +1,35 @@
Enqueue := function(v, x)
Add(v[1], x);
end;
Dequeue := function(v)
local n, x;
n := Size(v[2]);
if n = 0 then
v[2] := Reversed(v[1]);
v[1] := [ ];
n := Size(v[2]);
if n = 0 then
return fail;
fi;
fi;
return Remove(v[2], n);
end;
# a new queue
v := [[], []];
Enqueue(v, 3);
Enqueue(v, 4);
Enqueue(v, 5);
Dequeue(v);
# 3
Enqueue(v, 6);
Dequeue(v);
# 4
Dequeue(v);
# 5
Dequeue(v);
# 6
Dequeue(v);
# fail

View file

@ -0,0 +1,55 @@
package queue
// int queue
// the zero object is a valid queue ready to be used.
// items are pushed at tail, popped at head.
// tail = -1 means queue is full
type Queue struct {
b []string
head, tail int
}
func (q *Queue) Push(x string) {
switch {
// buffer full. reallocate.
case q.tail < 0:
next := len(q.b)
bigger := make([]string, 2*next)
copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head])
bigger[next] = x
q.b, q.head, q.tail = bigger, 0, next+1
// zero object. make initial allocation.
case len(q.b) == 0:
q.b, q.head, q.tail = make([]string, 4), 0 ,1
q.b[0] = x
// normal case
default:
q.b[q.tail] = x
q.tail++
if q.tail == len(q.b) {
q.tail = 0
}
if q.tail == q.head {
q.tail = -1
}
}
}
func (q *Queue) Pop() (string, bool) {
if q.head == q.tail {
return "", false
}
r := q.b[q.head]
if q.tail == -1 {
q.tail = q.head
}
q.head++
if q.head == len(q.b) {
q.head = 0
}
return r, true
}
func (q *Queue) Empty() bool {
return q.head == q.tail
}

View file

@ -0,0 +1,22 @@
class Queue {
private List buffer
public Queue(List buffer = new LinkedList()) {
assert buffer != null
assert buffer.empty
this.buffer = buffer
}
def push (def item) { buffer << item }
final enqueue = this.&push
def pop() {
if (this.empty) throw new NoSuchElementException('Empty Queue')
buffer.remove(0)
}
final dequeue = this.&pop
def getEmpty() { buffer.empty }
String toString() { "Queue:${buffer}" }
}

View file

@ -0,0 +1,27 @@
def q = new Queue()
assert q.empty
['Crosby', 'Stills'].each { q.push(it) }
assert !q.empty
['Nash', 'Young'].each { q.enqueue(it) }
println q
assert !q.empty
assert q.pop() == 'Crosby'
println q
assert !q.empty
assert q.dequeue() == 'Stills'
println q
assert !q.empty
assert q.pop() == 'Nash'
println q
assert !q.empty
q.push('Crazy Horse')
println q
assert q.dequeue() == 'Young'
println q
assert !q.empty
assert q.pop() == 'Crazy Horse'
println q
assert q.empty
try { q.pop() } catch (NoSuchElementException e) { println e }
try { q.dequeue() } catch (NoSuchElementException e) { println e }

View file

@ -0,0 +1,16 @@
data Fifo a = F [a] [a]
emptyFifo :: Fifo a
emptyFifo = F [] []
push :: Fifo a -> a -> Fifo a
push (F input output) item = F (item:input) output
pop :: Fifo a -> (Maybe a, Fifo a)
pop (F input (item:output)) = (Just item, F input output)
pop (F [] [] ) = (Nothing, F [] [])
pop (F input [] ) = pop (F [] (reverse input))
isEmpty :: Fifo a -> Bool
isEmpty (F [] []) = True
isEmpty _ = False

View file

@ -0,0 +1,34 @@
# Use a record to hold a Queue, using a list as the concrete implementation
record Queue(items)
procedure make_queue ()
return Queue ([])
end
procedure queue_push (queue, item)
put (queue.items, item)
end
# if the queue is empty, this will 'fail' and return nothing
procedure queue_pop (queue)
return pop (queue.items)
end
procedure queue_empty (queue)
return *queue.items = 0
end
# procedure to test class
procedure main ()
queue := make_queue()
# add the numbers 1 to 5
every (item := 1 to 5) do
queue_push (queue, item)
# pop them in the added order, and show a message when queue is empty
every (1 to 6) do {
write ("Popped value: " || queue_pop (queue))
if (queue_empty (queue)) then write ("empty queue")
}
end

View file

@ -0,0 +1,30 @@
# Use a class to hold a Queue, with a list as the concrete implementation
class Queue (items)
method push (item)
put (items, item)
end
# if the queue is empty, this will 'fail' and return nothing
method take ()
return pop (items)
end
method is_empty ()
return *items = 0
end
initially () # initialises the field on creating an instance
items := []
end
procedure main ()
queue := Queue ()
every (item := 1 to 5) do
queue.push (item)
every (1 to 6) do {
write ("Popped value: " || queue.take ())
if queue.is_empty () then write ("empty queue")
}
end

View file

@ -0,0 +1,16 @@
queue_fifo_=: ''
pop_fifo_=: verb define
r=. {. ::] queue
queue=: }.queue
r
)
push_fifo_=: verb define
queue=: queue,y
y
)
isEmpty_fifo_=: verb define
0=#queue
)

View file

@ -0,0 +1,10 @@
pop =: ( {.^:notnull ; }. )@: > @: ] /
push =: ( '' ; ,~ )& > /
tell_atom =: >& {.
tell_queue =: >& {:
is_empty =: '' -: 1 tell_queue
make_empty =: a: , a: [ ]
onto =: [ ; }.@]
notnull =: 0 ~: #

View file

@ -0,0 +1,40 @@
public class Queue<E>{
Node<E> head = null, tail = null;
static class Node<E>{
E value;
Node<E> next;
Node(E value, Node<E> next){
this.value= value;
this.next= next;
}
}
public Queue(){
}
public void enqueue(E value){ //standard queue name for "push"
Node<E> newNode= new Node<E>(value, null);
if(empty()){
head= newNode;
}else{
tail.next = newNode;
}
tail= newNode;
}
public E dequeue() throws java.util.NoSuchElementException{//standard queue name for "pop"
if(empty()){
throw new java.util.NoSuchElementException("No more elements.");
}
E retVal= head.value;
head= head.next;
return retVal;
}
public boolean empty(){
return head == null;
}
}

View file

@ -0,0 +1,5 @@
var fifo = [];
fifo.push(42); // Enqueue.
fifo.push(43);
var x = fifo.shift(); // Dequeue.
alert(x); // 42

View file

@ -0,0 +1,10 @@
function FIFO() {
this.data = new Array();
this.push = function(element) {this.data.push(element)}
this.pop = function() {return this.data.shift()}
this.empty = function() {return this.data.length == 0}
this.enqueue = this.push;
this.dequeue = this.pop;
}

View file

@ -0,0 +1,25 @@
Queue = {}
function Queue.new()
return { first = 0, last = -1 }
end
function Queue.push( queue, value )
queue.last = queue.last + 1
queue[queue.last] = value
end
function Queue.pop( queue )
if queue.first > queue.last then
return nil
end
local val = queue[queue.first]
queue[queue.first] = nil
queue.first = queue.first + 1
return val
end
function Queue.empty( queue )
return queue.first > queue.last
end

View file

@ -0,0 +1,10 @@
myfifo = {};
% push
myfifo{end+1} = x;
% pop
x = myfifo{1}; myfifo{1} = [];
% empty
isempty(myfifo)

View file

@ -0,0 +1,82 @@
%This class impliments a standard FIFO queue.
classdef FIFOQueue
properties
queue
end
methods
%Class constructor
function theQueue = FIFOQueue(varargin)
if isempty(varargin) %No input arguments
%Initialize the queue state as empty
theQueue.queue = {};
elseif (numel(varargin) > 1) %More than 1 input arg
%Make the queue the list of input args
theQueue.queue = varargin;
elseif iscell(varargin{:}) %If the only input is a cell array
%Make the contents of the cell array the elements in the queue
theQueue.queue = varargin{:};
else %There is one input argument that is not a cell
%Make that one arg the only element in the queue
theQueue.queue = varargin;
end
end
%push() - pushes a new element to the end of the queue
function push(theQueue,varargin)
if isempty(varargin)
theQueue.queue(end+1) = {[]};
elseif (numel(varargin) > 1) %More than 1 input arg
%Make the queue the list of input args
theQueue.queue( end+1:end+numel(varargin) ) = varargin;
elseif iscell(varargin{:}) %If the only input is a cell array
%Make the contents of the cell array the elements in the queue
theQueue.queue( end+1:end+numel(varargin{:}) ) = varargin{:};
else %There is one input argument that is not a cell
%Make that one arg the only element in the queue
theQueue.queue{end+1} = varargin{:};
end
%Makes changes to the queue permanent
assignin('caller',inputname(1),theQueue);
end
%pop() - pops the first element off the queue
function element = pop(theQueue)
if empty(theQueue)
error 'The queue is empty'
else
%Returns the first element in the queue
element = theQueue.queue{1};
%Removes the first element from the queue
theQueue.queue(1) = [];
%Makes changes to the queue permanent
assignin('caller',inputname(1),theQueue);
end
end
%empty() - Returns true if the queue is empty
function trueFalse = empty(theQueue)
trueFalse = isempty(theQueue.queue);
end
end %methods
end

View file

@ -0,0 +1,22 @@
>> myQueue = FIFOQueue({'hello'})
myQueue =
FIFOQueue
>> push(myQueue,'jello')
>> pop(myQueue)
ans =
hello
>> pop(myQueue)
ans =
jello
>> pop(myQueue)
??? Error using ==> FIFOQueue.FIFOQueue>FIFOQueue.pop at 61
The queue is empty

View file

@ -0,0 +1,3 @@
EmptyQ[a_] := Length[a] == 0
SetAttributes[Push, HoldAll]; Push[a_, elem_] := AppendTo[a, elem]
SetAttributes[Pop, HoldAllComplete]; Pop[a_] := If[EmptyQ[a], False, b = First[a]; Set[a, Most[a]]; b]

View file

@ -0,0 +1,18 @@
defstruct(queue(in=[], out=[]))$
enqueue(x, q) := (q@in: cons(x, q@in), done)$
dequeue(q) := (if not emptyp(q@out) then first([first(q@out), q@out: rest(q@out)])
elseif emptyp(q@in) then 'fail
else (q@out: reverse(q@in), q@in: [], first([first(q@out), q@out: rest(q@out)])))$
q:new(queue); /* queue([], []) */
enqueue(1, q)$
enqueue(2, q)$
enqueue(3, q)$
dequeue(q); /* 1 */
enqueue(4, q)$
dequeue(q); /* 2 */
dequeue(q); /* 3 */
dequeue(q); /* 4 */
dequeue(q); /* fail */

View file

@ -0,0 +1,35 @@
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
mqueue = ArrayDeque()
viewQueue(mqueue)
a = "Fred"
mqueue.push('') /* Puts an empty line onto the queue */
mqueue.push(a 2) /* Puts "Fred 2" onto the queue */
viewQueue(mqueue)
a = "Toft"
mqueue.add(a 2) /* Enqueues "Toft 2" */
mqueue.add('') /* Enqueues an empty line behind the last */
viewQueue(mqueue)
loop q_ = 1 while mqueue.size > 0
parse mqueue.pop.toString line
say q_.right(3)':' line
end q_
viewQueue(mqueue)
return
method viewQueue(mqueue = Deque) private static
If mqueue.size = 0 then do
Say 'Queue is empty'
end
else do
Say 'There are' mqueue.size 'elements in the queue'
end
return

View file

@ -0,0 +1,20 @@
module FIFO : sig
type 'a fifo
val empty: 'a fifo
val push: fifo:'a fifo -> item:'a -> 'a fifo
val pop: fifo:'a fifo -> 'a * 'a fifo
val is_empty: fifo:'a fifo -> bool
end = struct
type 'a fifo = 'a list * 'a list
let empty = [], []
let push ~fifo:(input,output) ~item = (item::input,output)
let is_empty ~fifo =
match fifo with
| [], [] -> true
| _ -> false
let rec pop ~fifo =
match fifo with
| input, item :: output -> item, (input,output)
| [], [] -> failwith "empty fifo"
| input, [] -> pop ([], List.rev input)
end

View file

@ -0,0 +1,28 @@
# open FIFO;;
# let q = empty ;;
val q : '_a FIFO.fifo = <abstr>
# is_empty q ;;
- : bool = true
# let q = push q 1 ;;
val q : int FIFO.fifo = <abstr>
# is_empty q ;;
- : bool = false
# let q =
List.fold_left push q [2;3;4] ;;
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 1
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 2
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 3
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
val v : int = 4
val q : int FIFO.fifo = <abstr>
# let v, q = pop q ;;
Exception: Failure "empty fifo".

View file

@ -0,0 +1,65 @@
'FIRST IN FIRST OUT
'==========
Class Queue
'==========
string buf
sys bg,i,le
method Encodelength(sys ls)
int p at (i+strptr buf)
p=ls
i+=sizeof int
end method
method push(string s)
ls=len s
if i+ls+8>le then
buf+=nuls 8000+ls*2 : le=len buf 'expand buf
end if
EncodeLength ls
mid buf,i+1,s
i+=ls
'EncodeLength ls
end method
method GetLength() as sys
if bg>=i then return -1 'buffer empty
int p at (bg+strptr buf)
bg+=sizeof int
return p
end method
method pop(string *s) as sys
sys ls=GetLength
if ls<0 then s="" : return ls 'empty buffer
s=mid buf,bg+1,ls
bg+=ls
if bg>1e6 then
buf=mid buf,bg+1 : bg=0 : le=len buf : i-=bg 'shrink buf
end if
end method
method clear()
buf="" : le="" : bg=0 : i=0
end method
end class
'====
'TEST
'====
Queue fifo
string s
'
fifo.push "HumptyDumpty"
fifo.push "Sat on a wall"
'
sys er
do
er=fifo.pop s
if er then print "(buffer empty)" : exit do
print s
end do

View file

@ -0,0 +1,34 @@
declare
fun {NewQueue}
Stream
WritePort = {Port.new Stream}
ReadPos = {NewCell Stream}
in
WritePort#ReadPos
end
proc {Push WritePort#_ Value}
{Port.send WritePort Value}
end
fun {Empty _#ReadPos}
%% the queue is empty if the value at the current
%% read position is not determined
{Not {IsDet @ReadPos}}
end
fun {Pop _#ReadPos}
%% blocks if empty
case @ReadPos of X|Xr then
ReadPos := Xr
X
end
end
Q = {NewQueue}
in
{Show {Empty Q}}
{Push Q 42}
{Show {Empty Q}}
{Show {Pop Q}}
{Show {Empty Q}}

View file

@ -0,0 +1,21 @@
class Fifo {
private $data = array();
public function push($element){
array_push($this->data, $element);
}
public function pop(){
if ($this->isEmpty()){
throw new Exception('Attempt to pop from an empty queue');
}
return array_shift($this->data);
}
//Alias functions
public function enqueue($element) { $this->push($element); }
public function dequeue() { return $this->pop(); }
//Note: PHP prevents a method name of 'empty'
public function isEmpty(){
return empty($this->data);
}
}

View file

@ -0,0 +1,9 @@
$foo = new Fifo();
$foo->push('One');
$foo->enqueue('Two');
$foo->push('Three');
echo $foo->pop(); //Prints 'One'
echo $foo->dequeue(); //Prints 'Two'
echo $foo->pop(); //Prints 'Three'
echo $foo->pop(); //Throws an exception

View file

@ -0,0 +1,28 @@
/* To push a node onto the end of the queue. */
push: procedure (tail);
declare tail handle (node), t handle (node);
t = new(:node:);
get (t => value);
if tail ^= bind(:null, node:) then
tail => link = t;
/* If the queue was non-empty, points the tail of the queue */
/* to the new node. */
tail = t; /* Point "tail" at the end of the queue. */
tail => link = bind(:node, null:);
end push;
/* To pop a node from the head of the queue. */
pop: procedure (head, val);
declare head handle (node), val fixed binary;
if head = bind(:node, null:) then signal error;
val = head => value;
head = head => pointer; /* pops the top node. */
if head = bind(:node, null:) then tail = head;
/* (If the queue is now empty, make tail null also.) */
end pop;
/* Queue status: the EMPTY function, returns true for empty queue. */
empty: procedure (h) returns (bit(1));
declare h handle (Node);
return (h = bind(:Node, null:) );
end empty;

View file

@ -0,0 +1,101 @@
program fifo(input, output);
type
pNode = ^tNode;
tNode = record
value: integer;
next: pNode;
end;
tFifo = record
first, last: pNode;
end;
procedure initFifo(var fifo: tFifo);
begin
fifo.first := nil;
fifo.last := nil
end;
procedure pushFifo(var fifo: tFifo; value: integer);
var
node: pNode;
begin
new(node);
node^.value := value;
node^.next := nil;
if fifo.first = nil
then
fifo.first := node
else
fifo.last^.next := node;
fifo.last := node
end;
function popFifo(var fifo: tFifo; var value: integer): boolean;
var
node: pNode;
begin
if fifo.first = nil
then
popFifo := false
else
begin
node := fifo.first;
fifo.first := fifo.first^.next;
value := node^.value;
dispose(node);
popFifo := true
end
end;
procedure testFifo;
var
fifo: tFifo;
procedure testpop(expectEmpty: boolean; expectedValue: integer);
var
i: integer;
begin
if popFifo(fifo, i)
then
if expectEmpty
then
writeln('Error! Expected empty, got ', i, '.')
else
if i = expectedValue
then
writeln('Ok, got ', i, '.')
else
writeln('Error! Expected ', expectedValue, ', got ', i, '.')
else
if expectEmpty
then
writeln('Ok, fifo is empty.')
else
writeln('Error! Expected ', expectedValue, ', found fifo empty.')
end;
begin
initFifo(fifo);
pushFifo(fifo, 2);
pushFifo(fifo, 3);
pushFifo(fifo, 5);
testpop(false, 2);
pushFifo(fifo, 7);
testpop(false, 3);
testpop(false, 5);
pushFifo(fifo, 11);
testpop(false, 7);
testpop(false, 11);
pushFifo(fifo, 13);
testpop(false, 13);
testpop(true, 0);
pushFifo(fifo, 17);
testpop(false, 17);
testpop(true, 0)
end;
begin
writeln('Testing fifo implementation ...');
testFifo;
writeln('Testing finished.')
end.

View file

@ -0,0 +1,13 @@
role FIFO {
method enqueue ( *@values ) { # Add values to queue, returns the number of values added.
self.push: @values;
return @values.elems;
}
method dequeue ( ) { # Remove and return the first value from the queue.
# Return Nil if queue is empty.
return self.elems ?? self.shift !! Nil;
}
method is-empty ( ) { # Check to see if queue is empty. Returns Boolean value.
return self.elems == 0;
}
}

View file

@ -0,0 +1,15 @@
my @queue does FIFO;
say @queue.is-empty; # -> Bool::True
say @queue.enqueue: <A B C>; # -> 3
say @queue.enqueue: Any; # -> 1
say @queue.enqueue: 7, 8; # -> 2
say @queue.is-empty; # -> Bool::False
say @queue.dequeue; # -> A
say @queue.elems; # -> 5
say @queue.dequeue; # -> B
say @queue.is-empty; # -> Bool::False
say @queue.enqueue('OHAI!'); # -> 1
say @queue.dequeue until @queue.is-empty; # -> C \n Any() \n 7 \n 8 \n OHAI!
say @queue.is-empty; # -> Bool::True
say @queue.dequeue; # ->

View file

@ -0,0 +1,4 @@
use Carp;
sub mypush (\@@) {my($list,@things)=@_; push @$list, @things}
sub mypop (\@) {my($list)=@_; @$list or croak "Empty"; shift @$list }
sub empty (@) {not @_}

View file

@ -0,0 +1,5 @@
my @fifo=qw(1 2 3 a b c);
mypush @fifo, 44, 55, 66;
mypop @fifo for 1 .. 6+3;
mypop @fifo; #empty now

View file

@ -0,0 +1,6 @@
(off Queue) # Clear Queue
(fifo 'Queue 1) # Store number '1'
(fifo 'Queue 'abc) # an internal symbol 'abc'
(fifo 'Queue "abc") # a transient symbol "abc"
(fifo 'Queue '(a b c)) # and a list (a b c)
Queue # Show the queue

View file

@ -0,0 +1,3 @@
% our queue is just [] and empty? is already defined.
/push {exch tadd}.
/pop {uncons exch}.

View file

@ -0,0 +1,11 @@
empty(U-V) :-
unify_with_occurs_check(U, V).
push(Queue, Value, NewQueue) :-
append_dl(Queue, [Value|X]-X, NewQueue).
% when queue is empty pop fails.
pop([X|V]-U, X, V-U) :-
\+empty([X|V]-U).
append_dl(X-Y, Y-Z, X-Z).

View file

@ -0,0 +1,38 @@
NewList MyStack()
Procedure Push(n)
Shared MyStack()
LastElement(MyStack())
AddElement(MyStack())
MyStack()=n
EndProcedure
Procedure Pop()
Shared MyStack()
Protected n
If FirstElement(MyStack()) ; e.g. Stack not empty
n=MyStack()
DeleteElement(MyStack(),1)
Else
Debug "Pop(), out of range. Error at line "+str(#PB_Compiler_Line)
EndIf
ProcedureReturn n
EndProcedure
Procedure Empty()
Shared MyStack()
If ListSize(MyStack())=0
ProcedureReturn #True
EndIf
ProcedureReturn #False
EndProcedure
;---- Example of implementation ----
Push(3)
Push(1)
Push(4)
While Not Empty()
Debug Pop()
Wend
;---- Now an extra Pop(), e.g. one to many ----
Debug Pop()

View file

@ -0,0 +1,45 @@
class FIFO(object):
def __init__(self, *args):
self.contents = list(args)
def __call__(self):
return self.pop()
def __len__(self):
return len(self.contents)
def pop(self):
return self.contents.pop(0)
def push(self, item):
self.contents.append(item)
def extend(self,*itemlist):
self.contents += itemlist
def empty(self):
return bool(self.contents)
def __iter__(self):
return self
def next(self):
if self.empty():
raise StopIteration
return self.pop()
if __name__ == "__main__":
# Sample usage:
f = FIFO()
f.push(3)
f.push(2)
f.push(1)
while not f.empty():
print f.pop(),
# >>> 3 2 1
# Another simple example gives the same results:
f = FIFO(3,2,1)
while not f.empty():
print f(),
# Another using the default "truth" value of the object
# (implicitly calls on the length() of the object after
# checking for a __nonzero__ method
f = FIFO(3,2,1)
while f:
print f(),
# Yet another, using more Pythonic iteration:
f = FIFO(3,2,1)
for i in f:
print i,

View file

@ -0,0 +1,15 @@
class FIFO: ## NOT a new-style class, must not derive from "object"
def __init__(self,*args):
self.contents = list(args)
def __call__(self):
return self.pop()
def empty(self):
return bool(self.contents)
def pop(self):
return self.contents.pop(0)
def __getattr__(self, attr):
return getattr(self.contents,attr)
def next(self):
if not self:
raise StopIteration
return self.pop()

View file

@ -0,0 +1,6 @@
from collections import deque
fifo = deque()
fifo. appendleft(value) # push
value = fifo.pop()
not fifo # empty
fifo.pop() # raises IndexError when empty

View file

@ -0,0 +1,48 @@
empty <- function() length(l) == 0
push <- function(x)
{
l <<- c(l, list(x))
print(l)
invisible()
}
pop <- function()
{
if(empty()) stop("can't pop from an empty list")
l[[1]] <<- NULL
print(l)
invisible()
}
l <- list()
empty()
# [1] TRUE
push(3)
# [[1]]
# [1] 3
push("abc")
# [[1]]
# [1] 3
# [[2]]
# [1] "abc"
push(matrix(1:6, nrow=2))
# [[1]]
# [1] 3
# [[2]]
# [1] "abc"
# [[3]]
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
empty()
# [1] FALSE
pop()
# [[1]]
# [1] 3
# [[2]]
# [1] "abc"
pop()
# [[1]]
# [1] 3
pop()
# list()
pop()
# Error in pop() : can't pop from an empty list

View file

@ -0,0 +1,39 @@
# The usual Scheme way : build a function that takes commands as parameters (it's like message passing oriented programming)
queue <- function() {
v <- list()
f <- function(cmd, val=NULL) {
if(cmd == "push") {
v <<- c(v, val)
invisible()
} else if(cmd == "pop") {
if(length(v) == 0) {
stop("empty queue")
} else {
x <- v[[1]]
v[[1]] <<- NULL
x
}
} else if(cmd == "length") {
length(v)
} else if(cmd == "empty") {
length(v) == 0
} else {
stop("unknown command")
}
}
f
}
# Create two queues
a <- queue()
b <- queue()
a("push", 1)
a("push", 2)
b("push", 3)
a("push", 4)
b("push", 5)
a("pop")
# [1] 1
b("pop")
# [1] 3

View file

@ -0,0 +1,30 @@
library(proto)
fifo <- proto(expr = {
l <- list()
empty <- function(.) length(.$l) == 0
push <- function(., x)
{
.$l <- c(.$l, list(x))
print(.$l)
invisible()
}
pop <- function(.)
{
if(.$empty()) stop("can't pop from an empty list")
.$l[[1]] <- NULL
print(.$l)
invisible()
}
})
#The following code provides output that is the same as the previous example.
fifo$empty()
fifo$push(3)
fifo$push("abc")
fifo$push(matrix(1:6, nrow=2))
fifo$empty()
fifo$pop()
fifo$pop()
fifo$pop()
fifo$pop()

View file

@ -0,0 +1,33 @@
rebol [
Title: "FIFO"
Author: oofoe
Date: 2009-12-11
URL: http://rosettacode.org/wiki/FIFO
]
; Define fifo class:
fifo: make object! [
queue: copy []
push: func [x][append queue x]
pop: func [/local x][ ; Make 'x' local so it won't pollute global namespace.
if empty [return none]
x: first queue remove queue x]
empty: does [empty? queue]
]
; Create and populate a FIFO:
q: make fifo []
q/push 'a
q/push 2
q/push USD$12.34 ; Did I mention that REBOL has 'money!' datatype?
q/push [Athos Porthos Aramis] ; List elements pushed on one by one.
q/push [[Huey Dewey Lewey]] ; This list is preserved as a list.
; Dump it out, with narrative:
print rejoin ["Queue is " either q/empty [""]["not "] "empty."]
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]

View file

@ -0,0 +1,20 @@
/*REXX program to demonstrate FIFO queue usage by some simple operations*/
call viewQueue
a="Fred"
push /*puts a "null" on top of queue.*/
push a 2 /*puts "Fred 2" on top of queue.*/
call viewQueue
queue "Toft 2" /*put "Toft 2" on queue bottom.*/
queue /*put a "null" on queue bottom.*/
call viewQueue
do n=1 while queued()\==0
parse pull xxx
say "queue entry" n': ' xxx
end /*n*/
call viewQueue
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────viewQueue subroutine────────────────*/
viewQueue: if queued()==0 then say 'Queue is empty'
else say 'There are' queued() 'elements in the queue'
return

View file

@ -0,0 +1,57 @@
require 'forwardable'
# A FIFO queue contains elements in first-in, first-out order.
# FIFO#push adds new elements to the end of the queue;
# FIFO#pop or FIFO#shift removes elements from the front.
class FIFO
extend Forwardable
# Creates a FIFO containing _objects_.
def self.[](*objects)
new.push(*objects)
end
# Creates an empty FIFO.
def initialize; @ary = []; end
# Appends _objects_ to the end of this FIFO. Returns self.
def push(*objects)
@ary.push(*objects)
self
end
alias << push
alias enqueue push
##
# :method: pop
# :call-seq:
# pop -> obj or nil
# pop(n) -> ary
#
# Removes an element from the front of this FIFO, and returns it.
# Returns nil if the FIFO is empty.
#
# If passing a number _n_, removes the first _n_ elements, and returns
# an Array of them. If this FIFO contains fewer than _n_ elements,
# returns them all. If this FIFO is empty, returns an empty Array.
def_delegator :@ary, :shift, :pop
alias shift pop
alias dequeue shift
##
# :method: empty?
# Returns true if this FIFO contains no elements.
def_delegator :@ary, :empty?
##
# :method: size
# Returns the number of elements in this FIFO.
def_delegator :@ary, :size
alias length size
# Converts this FIFO to a String.
def to_s
"FIFO#{@ary.inspect}"
end
alias inspect to_s
end

View file

@ -0,0 +1,16 @@
f = FIFO.new
f.empty? # => true
f.pop # => nil
f.pop(2) # => []
f.push(14) # => FIFO[14]
f << "foo" << [1,2,3] # => FIFO[14, "foo", [1, 2, 3]]
f.enqueue("bar", Hash.new, "baz")
# => FIFO[14, "foo", [1, 2, 3], "bar", {}, "baz"]
f.size # => 6
f.pop(3) # => [14, "foo", [1, 2, 3]]
f.dequeue # => "bar"
f.empty? # => false
g = FIFO[:a, :b, :c]
g.pop(2) # => [:a, :b]
g.pop(2) # => [:c]
g.pop(2) # => []

View file

@ -0,0 +1,34 @@
class Queue[T] {
private[this] class Node[T](val value:T) {
var next:Option[Node[T]]=None
def append(n:Node[T])=next=Some(n)
}
private[this] var head:Option[Node[T]]=None
private[this] var tail:Option[Node[T]]=None
def isEmpty=head.isEmpty
def enqueue(item:T)={
val n=new Node(item)
if(isEmpty) head=Some(n) else tail.get.append(n)
tail=Some(n)
}
def dequeue:T=head match {
case Some(item) => head=item.next; item.value
case None => throw new java.util.NoSuchElementException()
}
def front:T=head match {
case Some(item) => item.value
case None => throw new java.util.NoSuchElementException()
}
def iterator: Iterator[T]=new Iterator[T]{
private[this] var it=head;
override def hasNext=it.isDefined
override def next:T={val n=it.get; it=n.next; n.value}
}
override def toString()=iterator.mkString("Queue(", ", ", ")")
}

View file

@ -0,0 +1,11 @@
val q=new Queue[Int]()
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
q enqueue 1
q enqueue 2
q enqueue 3
println("queue = " + q)
println("front = " + q.front)
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)

View file

@ -0,0 +1,15 @@
(define (make-queue)
(make-vector 1 '()))
(define (push a queue)
(vector-set! queue 0 (append (vector-ref queue 0) (list a))))
(define (empty? queue)
(null? (vector-ref queue 0)))
(define (pop queue)
(if (empty? queue)
(error "can not pop an empty queue")
(let ((ret (car (vector-ref queue 0))))
(vector-set! queue 0 (cdr (vector-ref queue 0)))
ret)))

View file

@ -0,0 +1,25 @@
(define (make-queue)
(let ((q (cons '() '())))
(lambda (cmd . arg)
(case cmd
((empty?) (null? (car q)))
((put) (let ((a (cons (car arg) '())))
(if (null? (car q))
(begin (set-car! q a) (set-cdr! q a))
(begin (set-cdr! (cdr q) a) (set-cdr! q a)))))
((get) (if (null? (car q)) 'empty
(let ((x (caar q)))
(set-car! q (cdar q))
(if (null? (car q)) (set-cdr! q '()))
x)))
))))
(define q (make-queue))
(q 'put 1)
(q 'put 6)
(q 'get)
; 1
(q 'get)
; 6
(q 'get)
; empty

View file

@ -0,0 +1,7 @@
collections define: #Queue &parents: {ExtensibleArray}.
q@(Queue traits) isEmpty [resend].
q@(Queue traits) push: obj [q addLast: obj].
q@(Queue traits) pop [q removeFirst].
q@(Queue traits) pushAll: c [q addAllLast: c].
q@(Queue traits) pop: n [q removeFirst: n].

View file

@ -0,0 +1,20 @@
OrderedCollection extend [
push: obj [ ^(self add: obj) ]
pop [
(self isEmpty) ifTrue: [
SystemExceptions.NotFound signalOn: self
reason: 'queue empty'
] ifFalse: [
^(self removeFirst)
]
]
]
|f|
f := OrderedCollection new.
f push: 'example'; push: 'another'; push: 'last'.
f pop printNl.
f pop printNl.
f pop printNl.
f isEmpty printNl.
f pop. "queue empty error"

View file

@ -0,0 +1,12 @@
signature QUEUE =
sig
type 'a queue
val empty_queue: 'a queue
exception Empty
val enq: 'a queue -> 'a -> 'a queue
val deq: 'a queue -> ('a * 'a queue)
val empty: 'a queue -> bool
end;

View file

@ -0,0 +1,16 @@
structure Queue:> QUEUE =
struct
type 'a queue = 'a list
val empty_queue = nil
exception Empty
fun enq q x = q @ [x]
fun deq nil = raise Empty
| deq (x::q) = (x, q)
fun empty nil = true
| empty _ = false
end;

View file

@ -0,0 +1,31 @@
proc push {stackvar value} {
upvar 1 $stackvar stack
lappend stack $value
}
proc pop {stackvar} {
upvar 1 $stackvar stack
set value [lindex $stack 0]
set stack [lrange $stack 1 end]
return $value
}
proc size {stackvar} {
upvar 1 $stackvar stack
llength $stack
}
proc empty {stackvar} {
upvar 1 $stackvar stack
expr {[size stack] == 0}
}
proc peek {stackvar} {
upvar 1 $stackvar stack
lindex $stack 0
}
set Q [list]
empty Q ;# ==> 1 (true)
push Q foo
empty Q ;# ==> 0 (false)
push Q bar
peek Q ;# ==> foo
pop Q ;# ==> foo
peek Q ;# ==> bar

View file

@ -0,0 +1,10 @@
package require struct::queue
struct::queue Q
Q size ;# ==> 0
Q put a b c d e
Q size ;# ==> 5
Q peek ;# ==> a
Q get ;# ==> a
Q peek ;# ==> b
Q pop 4 ;# ==> b c d e
Q size ;# ==> 0

View file

@ -0,0 +1,4 @@
init() {echo > fifo}
push() {echo $1 >> fifo }
pop() {head -1 fifo ; (cat fifo | tail -n +2)|sponge fifo}
empty() {cat fifo | wc -l}

View file

@ -0,0 +1,6 @@
push me; push you; push us; push them
|pop;pop;pop;pop
me
you
us
them

View file

@ -0,0 +1,4 @@
[fifo_create []].
[fifo_push swap cons].
[fifo_pop [[*rest a] : [*rest] a] view].
[fifo_empty? dup empty?].

View file

@ -0,0 +1,8 @@
|fifo_create 3 fifo_push 4 fifo_push 5 fifo_push ??
=[5 4 3]
|fifo_empty? puts
=false
|fifo_pop put fifo_pop put fifo_pop put
=3 4 5
|fifo_empty? puts
=true

View file

@ -0,0 +1,48 @@
include c:\cxpl\codes;
def Size=8;
int Fifo(Size);
int In, Out; \fill and empty indexes into Fifo
proc Push(A); \Add integer A to queue
int A; \(overflow not detected)
[Fifo(In):= A;
In:= In+1;
if In >= Size then In:= 0;
];
func Pop; \Return first integer in queue
int A;
[if Out=In then \if popping empty queue
[Text(0, "Error"); exit 1]; \ then exit program with error code 1
A:= Fifo(Out);
Out:= Out+1;
if Out >= Size then Out:= 0;
return A;
];
func Empty; \Return 'true' if queue is empty
return In = Out;
[In:= 0; Out:= 0;
Push(0);
Text(0, if Empty then "true" else "false"); CrLf(0);
IntOut(0, Pop); CrLf(0);
Push(1);
Push(2);
Push(3);
IntOut(0, Pop); CrLf(0);
IntOut(0, Pop); CrLf(0);
IntOut(0, Pop); CrLf(0);
Text(0, if Empty then "true" else "false"); CrLf(0);
\A 256-byte queue is built in as device 8:
OpenI(8); OpenO(8);
ChOut(8, ^0); \push
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(8, ^1); \push
ChOut(8, ^2); \push
ChOut(8, ^3); \push
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
ChOut(0, ChIn(8)); CrLf(0); \pop
]