typestar

Subranges and Ord in Delphi

A TLane = 1..4 subrange indexes an array of lap times, and Ord round-trips a letter.

program SubrangeOrd;
type
  TLane = 1..4;              // a subrange narrows a type's valid values
var
  Splits: array[TLane] of Integer;
  Lane: TLane;
  Grade: Char;
begin
  for Lane := Low(Splits) to High(Splits) do  // a subrange indexes arrays
    Splits[Lane] := 60 + Lane;
  WriteLn('lane 3 swam ', Splits[3], ' seconds');
  Grade := 'b';
  // Ord reads a character's code and Chr turns the code back.
  WriteLn(Grade, ' is code ', Ord(Grade), ', back to ', Chr(Ord(Grade)));
end.

How it works

  1. TLane = 1..4; narrows the values, and Splits: array[TLane] of Integer indexes by it.
  2. for Lane := Low(Splits) to High(Splits) do walks the subrange from end to end.
  3. Ord(Grade) gives the code for 'b', and Chr(Ord(Grade)) turns it back.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
465
Tokens
106
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 85 seconds.

Type this snippet

Step 3 of 3 in Enums & sets, step 18 of 27 in Language basics.

← Previous Next →