12.8.6 Set operators

The following operations on sets can be performed with operators: union, difference, symmetric difference, inclusion and intersection. The operators are listed in table (12.6).


Table 12.6: Set operators

OperationAction


+ Union
- Difference operator
* Intersection
>< Symmetric difference
<= Contains
>= Left hand side set is a superset of the one on the right
in check whether an element is in a set

In addition to the above operators, elements can be added or removed from the set with the Include or Exclude procedures:

include
includes an element in the set.
exclude
excludes an element from the set.

The set type of the operands or arguments must be the same, or an error will be generated by the compiler.

The following program gives some valid examples of set operations:

Type  
  Day = (mon,tue,wed,thu,fri,sat,sun);  
  Days = set of Day;  
 
Procedure PrintDays(W : Days);  
Const  
  DayNames : array [Day] of String[3]  
           = ('mon','tue','wed','thu',  
              'fri','sat','sun');  
Var  
  D : Day;  
  S : String;  
begin  
  S:='';  
  For D:=Mon to Sun do  
    if D in W then  
      begin  
      If (S<>'') then S:=S+',';  
      S:=S+DayNames[D];  
      end;  
  Writeln('[',S,']');  
end;  
 
Const  
  WorkWeek = [mon,tue,wed,thu,fri];  
  WeekEnd = [sat,sun];  
 
Var  
  W : Days;  
 
begin  
   W:=[mon,tue]+[wed,thu,fri]; // equals [mon,tue,wed,thu,fri]  
   PrintDays(W);  
   W:=[mon,tue,wed]-[wed];     // equals [mon,tue]  
   PrintDays(W);  
   W:=[mon,tue,wed]-[wed,thu];     // also equals [mon,tue]  
   PrintDays(W);  
   W:=[mon,tue,wed]*[wed,thu,fri]; // equals [wed]  
   PrintDays(W);  
   W:=[mon,tue,wed]><[wed,thu,fri]; // equals [mon,tue,thu,fri]  
   PrintDays(W);  
   if [mon,tue]<=WorkWeek then  
     Writeln('Must work on monday and tuesday');  
   if Weekend>=[sun] then  
     Writeln('Can rest on sunday');  
end.

As can be seen, the union is equivalent to a binary OR, while the intersection is equivalent to a binary AND, and the symmetric difference equals a XOR operation.

The Include and Exclude operations are equivalent to a union or a difference with a set of one element. Thus,

  Include(W,wed);

is equivalent to

  W:=W+[wed];

and

  Exclude(W,wed);

is equivalent to

  W:=W-[wed];

The In operation results in a True if the left operand (an element) is included of the right operand (a set), the result will be False otherwise.