Range Over Built in Pascal

Let’s translate the provided Go code example to Pascal. Here’s the content in Markdown format suitable for Hugo.

Range over Built-in Types

Explanation

range iterates over elements in a variety of built-in data structures. Let’s see how to use range with some of the data structures we’ve already learned.

Code Example

program RangeOverBuiltInTypes;
uses sysutils;

var
  nums: array of Integer;
  sum, i, num: Integer;
  kvs: TStringList;
  key: string;

begin
  // Here we use a loop to sum the numbers in an array.
  SetLength(nums, 3);
  nums[0] := 2;
  nums[1] := 3;
  nums[2] := 4;
  
  sum := 0;
  for i := 0 to High(nums) do
  begin
    sum := sum + nums[i];
  end;
  Writeln(Format('sum: %d', [sum]));

  // Use another loop to find the index of the number 3.
  for i := 0 to High(nums) do
  begin
    if nums[i] = 3 then
    begin
      Writeln(Format('index: %d', [i]));
    end;
  end;

  // Iterate over key/value pairs in a TStringList.
  kvs := TStringList.Create;
  try
    kvs.Add('a=apple');
    kvs.Add('b=banana');

    for i := 0 to kvs.Count - 1 do
    begin
      Writeln(Format('%s -> %s', [kvs.Names[i], kvs.ValueFromIndex[i]]));
    end;

    // Iterate over just the keys.
    for i := 0 to kvs.Count - 1 do
    begin
      Writeln(Format('key: %s', [kvs.Names[i]]));
    end;
  finally
    kvs.Free;
  end;

  // Iterate over the characters in a string.
  for i := 1 to Length('go') do
  begin
    Writeln(Format('%d %d', [i - 1, Ord('go'[i])]));
  end;
end.

Explanation

Here we use a loop to sum the numbers in an array. Arrays work like this too.

nums is defined as an array of integers. We initialize it with values 2, 3, and 4.

We use a for loop to iterate over the array, summing the values, and then print the result.

On arrays, we often need both the index and value for each entry. In some cases, we might only want the index.

We use another for loop to check for the value 3 in the array and print its index when found.

TStringList is Pascal’s way of handling key-value data structures similar to maps in other languages.

We create a TStringList named kvs, add some key-value pairs, and then iterate over the list to print each key and its corresponding value.

We can also iterate over just the keys of a map.

Finally, we use a simple for loop to iterate over characters in a string. Pascal treats strings as arrays of characters, and we can print both the index and the ASCII value of each character.