
Data Structure

This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.
 Illustration of FIFO behavior
Task

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.


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


go =>
  println("Test 1"),
  queue_test1,
  nl.
 
empty(Q) => Q = [].
push(Queue, Value) = Q2 =>
  Q2 = [Value] ++ Queue.
pop(Q,_) = _, Q==[] ; var(Q) => 
   throw $error(empty_queue,pop,'Q'=Q).
pop(Queue,Q2) = Queue.last() =>
   Q2 = [Queue[I] : I in 1..Queue.len-1].
 
queue_test1 =>
 
    % create an empty queue
    println("Start test 2"),
    empty(Q0),
    printf("Create queue %w%n%n", Q0),
 
    % add numbers 1 and 2
    println("Add numbers 1 and 2 : "),
    Q1 = Q0.push(1),
    Q2 = Q1.push(2),
 
    % display queue
    printf("Q2: %w\n\n", Q2),
 
    % pop element
    V = Q2.pop(Q3),
 
    % display results
    printf("Pop : Value: %w Queue: %w\n\n", V, Q3),
 
    % test the queue
    print("Test of the queue: "),
    ( Q3.empty() -> println("Queue empty"); println("Queue not empty") ), 
    nl,
 
    % pop the elements
    print("Pop the queue : "),
    V1 = Q3.pop(Q4),
    printf("Value %w Queue : %w%n%n", V1, Q4),
 
    println("Pop empty queue:"),
    catch(_V = Q4.pop(_Q5),Exception,println(Exception)),
    nl,
 
    println("\nEnd of tests.").