Set Operators

The in operator examines membership of the set. Response in ['y', 'Y', 'n', 'N'] is True when Response is 'y', 'Y', 'n' or 'N' and False otherwise. Another useful set for validation purposes is ['A' .. 'Z', 'a' .. 'z', '-', CHR(39)], containing the acceptable characters for British surnames.

Three other commonly used set operators are + (union), - (difference), and * (intersection). If Set1 contains 1, 2, 4 and 5 and Set2 contains 3, 4, 5 and 6 then:

  • Set1 + Set2 contains 1, 2, 3, 4, 5 and 6 (all of the values);
  • Set1 – Set2 contains 1 and 2 (values from Set1 that are not in Set2);
  • Set1 * Set2 contains 4 and 5 (values in both sets).

The following program demonstrates the use of these operators.

program DieSet;
  {$APPTYPE CONSOLE}
uses
  Sysutils;
type
  TDieSet = set of 1..6;
var
  Set1 : TDieSet = [1, 2, 4, 5];
  Set2 : TDieSet = [3, 4, 5, 6];
  Set3 : TDieSet;

procedure Display(DisplayedSet : TDieSet);
var
  Count : integer;
begin
  for Count := 1 to 6 do
    begin
      if Count in DisplayedSet then
        write(Count,' '); //Membership
    end;
  writeln;
end;

begin
  write('Set1: ');
  Display(Set1);
  write('Set2: ');
  Display(Set2);
  Set3 := Set1 + Set2;   //Union
  write('Union: ');
  Display(Set3);
  Set3 := Set1 - Set2;   //Difference
  write('Difference (Set1 - Set2): ');
  Display(Set3);
  Set3 := Set1 * Set2;   //Intersection
  write('Intersection: ');
  Display(Set3);
  readln;
end.
Programming - a skill for life!

Declaration, assignment, operators and functions of sets