Range Over Channels in Pascal

program RangeOverChannels;

uses
  SysUtils;

type
  TStringQueue = record
    Items: array of string;
    Count: Integer;
  end;

procedure Enqueue(var Queue: TStringQueue; const Item: string);
begin
  SetLength(Queue.Items, Queue.Count + 1);
  Queue.Items[Queue.Count] := Item;
  Inc(Queue.Count);
end;

function Dequeue(var Queue: TStringQueue): string;
var
  i: Integer;
begin
  if Queue.Count > 0 then
  begin
    Result := Queue.Items[0];
    for i := 1 to Queue.Count - 1 do
      Queue.Items[i - 1] := Queue.Items[i];
    Dec(Queue.Count);
    SetLength(Queue.Items, Queue.Count);
  end
  else
    Result := '';
end;

var
  Queue: TStringQueue;
  Item: string;

begin
  // We'll iterate over 2 values in the `Queue` record.
  Enqueue(Queue, 'one');
  Enqueue(Queue, 'two');

  // This loop iterates over each element as it's
  // received from `Queue`. Because we've added only
  // two elements, the iteration terminates after
  // receiving those 2 elements.
  while Queue.Count > 0 do
  begin
    Item := Dequeue(Queue);
    WriteLn(Item);
  end;
end.

In this Pascal example, we’ve created a simple queue structure to mimic the behavior of channels in Go. The TStringQueue record type represents our queue, and we’ve implemented Enqueue and Dequeue procedures to add and remove items from the queue.

The main program creates a queue, adds two items to it (‘one’ and ’two’), and then iterates over the queue, printing each item. This mimics the behavior of the original Go program that used a buffered channel.

To run this program, you would typically save it as a .pas file (e.g., RangeOverChannels.pas) and compile it using a Pascal compiler like Free Pascal:

$ fpc RangeOverChannels.pas
$ ./RangeOverChannels
one
two

This example demonstrates how to iterate over a collection of items in Pascal, which is conceptually similar to ranging over a channel in other languages. While Pascal doesn’t have built-in concurrency primitives like channels, this queue-based approach provides a way to process a sequence of items one at a time.