ZetCode

Modula-2 sets

last modified November 26, 2026 Modula-2

A set holds any combination of the values of an enumeration, a subrange or CHAR, each value at most once. Sets are built into Modula-2: a set is stored as a row of bits, one for each possible value, so testing membership and combining two sets are fast operations.

A set type

SET OF T declares a set type whose elements are values of T. A set value is written as the name of the set type followed by the elements in braces. The operator IN tests whether a value is an element of a set.

pizza.mod
MODULE pizza;

FROM InOut IMPORT WriteString, WriteLn;

TYPE
  Topping = (Cheese, Ham, Mushrooms, Olives, Onion, Pepper);
  Toppings = SET OF Topping;

VAR
  order: Toppings;

BEGIN
  order := Toppings{Cheese, Mushrooms, Olives};
  IF Olives IN order THEN
    WriteString("with olives");
    WriteLn
  END;
  IF NOT (Ham IN order) THEN
    WriteString("vegetarian");
    WriteLn
  END;
  IF order # Toppings{} THEN
    WriteString("not a plain base");
    WriteLn
  END
END pizza.

Toppings is a set of Topping values, and order holds three of them. IN has the precedence of a comparison, so NOT (Ham IN order) needs the parentheses. Toppings{} is the empty set; # compares two sets.

$ gm2 pizza.mod -o pizza
$ ./pizza
with olives
vegetarian
not a plain base

INCL and EXCL

INCL(s, x) adds the element x to the set variable s, and EXCL(s, x) removes it. A set has no order and no duplicates, so a program prints a set by testing every possible element.

order.mod
MODULE order;

FROM InOut IMPORT WriteString, WriteLn;

TYPE
  Topping = (Cheese, Ham, Mushrooms, Olives, Onion, Pepper);
  Toppings = SET OF Topping;

VAR
  pizza: Toppings;

PROCEDURE WriteToppings(s: Toppings);
VAR
  t: Topping;
BEGIN
  WriteString("{");
  FOR t := MIN(Topping) TO MAX(Topping) DO
    IF t IN s THEN
      CASE t OF
        Cheese: WriteString(" cheese") |
        Ham: WriteString(" ham") |
        Mushrooms: WriteString(" mushrooms") |
        Olives: WriteString(" olives") |
        Onion: WriteString(" onion") |
        Pepper: WriteString(" pepper")
      END
    END
  END;
  WriteString(" }");
  WriteLn
END WriteToppings;

BEGIN
  pizza := Toppings{};
  WriteToppings(pizza);
  INCL(pizza, Cheese);
  INCL(pizza, Ham);
  INCL(pizza, Pepper);
  WriteToppings(pizza);
  EXCL(pizza, Ham);
  INCL(pizza, Cheese);
  WriteToppings(pizza);
  pizza := Toppings{Cheese..Olives};
  WriteToppings(pizza)
END order.

WriteToppings walks through all toppings from MIN(Topping) to MAX(Topping) and prints those that are in the set. The second INCL(pizza, Cheese) changes nothing, because cheese is already in the set. A range such as Cheese..Olives in a set constructor stands for all the values from the first to the last.

$ gm2 order.mod -o order
$ ./order
{ }
{ cheese ham pepper }
{ cheese pepper }
{ cheese ham mushrooms olives }

Set operators

Four operators combine two sets of the same type: + is the union, * the intersection, - the difference and / the symmetric difference, the elements in exactly one of the two sets.

shifts.mod
MODULE shifts;

FROM InOut IMPORT WriteString, WriteLn;

TYPE
  Day = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  Days = SET OF Day;

VAR
  anna, ben: Days;

PROCEDURE WriteDays(label: ARRAY OF CHAR; s: Days);
VAR
  d: Day;
BEGIN
  WriteString(label);
  FOR d := MIN(Day) TO MAX(Day) DO
    IF d IN s THEN
      CASE d OF
        Mon: WriteString(" Mon") |
        Tue: WriteString(" Tue") |
        Wed: WriteString(" Wed") |
        Thu: WriteString(" Thu") |
        Fri: WriteString(" Fri") |
        Sat: WriteString(" Sat") |
        Sun: WriteString(" Sun")
      END
    END
  END;
  WriteLn
END WriteDays;

BEGIN
  anna := Days{Mon, Tue, Wed, Sat};
  ben := Days{Wed..Fri, Sat};
  WriteDays("anna:        ", anna);
  WriteDays("ben:         ", ben);
  WriteDays("either:      ", anna + ben);
  WriteDays("both:        ", anna * ben);
  WriteDays("only anna:   ", anna - ben);
  WriteDays("only one:    ", anna / ben);
  WriteDays("nobody:      ", Days{Mon..Sun} - (anna + ben))
END shifts.

anna and ben are the days two people work. The union gives the days when at least one of them works, the intersection the days when both work, and the difference the days of Anna's that Ben does not share. The last line subtracts the union from the whole week, leaving the days on which nobody works. Each difference here has a variable operand. In gm2 15.2 the difference of two set constants is unreliable: CharSet{',', 'a'} - CharSet{'a', 'z'} wrongly leaves out the comma, and a constant declared with - can crash the compiler.

$ gm2 shifts.mod -o shifts
$ ./shifts
anna:         Mon Tue Wed Sat
ben:          Wed Thu Fri Sat
either:       Mon Tue Wed Thu Fri Sat
both:         Wed Sat
only anna:    Mon Tue
only one:     Mon Tue Thu Fri
nobody:       Sun

Comparing sets

= and # test whether two sets have the same elements. a <= b is true when a is a subset of b, and a >= b when a contains b.

compare.mod
MODULE compare;

FROM InOut IMPORT WriteString, WriteLn;

TYPE
  Day = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  Days = SET OF Day;

VAR
  open, weekend, visit: Days;

PROCEDURE Answer(question: ARRAY OF CHAR; yes: BOOLEAN);
BEGIN
  WriteString(question);
  IF yes THEN
    WriteString("yes")
  ELSE
    WriteString("no")
  END;
  WriteLn
END Answer;

BEGIN
  open := Days{Tue..Sun};
  weekend := Days{Sat, Sun};
  visit := Days{Mon, Sat};

  Answer("open every weekend day? ", weekend <= open);
  Answer("open on every visit day? ", visit <= open);
  Answer("open days include the weekend? ", open >= weekend);
  Answer("weekend is Sat and Sun? ", weekend = Days{Sun, Sat});
  Answer("visit differs from weekend? ", visit # weekend);
  Answer("closed on some visit day? ", visit - open # Days{})
END compare.

A shop is open from Tuesday to Sunday. The weekend is a subset of the open days, but the planned visits are not, because one of them falls on a Monday. The order of the elements in a constructor does not matter, so Days{Sun, Sat} equals weekend. The last question subtracts the open days from the visits and checks whether anything is left.

$ gm2 compare.mod -o compare
$ ./compare
open every weekend day? yes
open on every visit day? no
open days include the weekend? yes
weekend is Sat and Sun? yes
visit differs from weekend? yes
closed on some visit day? yes

Sets of numbers

The element type may be a subrange of the whole numbers. Wirth's PIM allows only small sets, limited to the bits of a machine word, and some compilers keep that limit; GNU Modula-2 accepts much larger ones.

multiples.mod
MODULE multiples;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

CONST
  Limit = 60;

TYPE
  Numbers = SET OF [0..Limit];

VAR
  threes, fives: Numbers;
  n: CARDINAL;

PROCEDURE WriteNumbers(label: ARRAY OF CHAR; s: Numbers);
VAR
  i: CARDINAL;
BEGIN
  WriteString(label);
  FOR i := 0 TO Limit DO
    IF i IN s THEN
      WriteCard(i, 3)
    END
  END;
  WriteLn
END WriteNumbers;

BEGIN
  threes := Numbers{};
  fives := Numbers{};
  FOR n := 3 TO Limit BY 3 DO
    INCL(threes, n)
  END;
  FOR n := 5 TO Limit BY 5 DO
    INCL(fives, n)
  END;
  WriteNumbers("by 3 and 5:", threes * fives);
  WriteNumbers("by 5 only: ", fives - threes);
  WriteNumbers("teens:     ", Numbers{13..19} - threes - fives);
  WriteString("bytes in the set: ");
  WriteCard(SIZE(Numbers), 0);
  WriteLn
END multiples.

threes collects the multiples of 3 up to 60 and fives the multiples of 5. Their intersection holds the multiples of 15. The teens are written as the range 13..19, from which both sets are subtracted. The 61 possible elements take 8 bytes, one bit each, rounded up.

$ gm2 multiples.mod -o multiples
$ ./multiples
by 3 and 5: 15 30 45 60
by 5 only:   5 10 20 25 35 40 50 55
teens:      13 14 16 17 19
bytes in the set: 8

BITSET

BITSET is a predefined set of small cardinals, one for each bit of a word. Its constructor needs no type name: {0, 2} is a BITSET. The data types article introduced it; here it holds flags.

flags.mod
MODULE flags;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

CONST
  CanRead = 2;
  CanWrite = 1;
  CanExecute = 0;

VAR
  mode: BITSET;
  bit: CARDINAL;

PROCEDURE ShowBits(s: BITSET);
VAR
  i: CARDINAL;
BEGIN
  FOR i := 0 TO 8 DO
    IF i IN s THEN
      WriteCard(i, 2)
    END
  END;
  WriteLn
END ShowBits;

BEGIN
  mode := {CanRead, CanWrite};
  ShowBits(mode);
  INCL(mode, CanExecute);
  ShowBits(mode);
  EXCL(mode, CanWrite);
  ShowBits(mode);

  mode := {0..8};
  bit := 4;
  EXCL(mode, bit);
  ShowBits(mode);
  WriteString("bits in a BITSET: ");
  WriteCard(SIZE(BITSET) * 8, 0);
  WriteLn
END flags.

The constants name the bits of a file mode: {CanRead, CanWrite} sets bits 2 and 1. INCL and EXCL switch single bits on and off, and {0..8} sets nine bits at once. In GNU Modula-2 a BITSET has 32 elements, 0 to 31.

$ gm2 flags.mod -o flags
$ ./flags
 1 2
 0 1 2
 0 2
 0 1 2 3 5 6 7 8
bits in a BITSET: 32

Sets of characters

SET OF CHAR holds any combination of the 256 characters. A set of characters describes a class, such as vowels or letters, and IN tests a character against it in one step.

vowels.mod
MODULE vowels;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

TYPE
  CharSet = SET OF CHAR;

CONST
  Vowels = CharSet{'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
  Letters = CharSet{'a'..'z', 'A'..'Z'};

VAR
  text: ARRAY [0..63] OF CHAR;
  i, nv, nc: CARDINAL;
  ch: CHAR;

BEGIN
  text := "Modula-2 was designed by Niklaus Wirth in 1978.";

  nv := 0;
  nc := 0;
  i := 0;
  WHILE (i <= HIGH(text)) AND (text[i] # 0C) DO
    ch := text[i];
    IF ch IN Vowels THEN
      INC(nv)
    ELSIF ch IN Letters THEN
      INC(nc)
    END;
    INC(i)
  END;
  WriteString(text);
  WriteLn;
  WriteString("vowels: ");
  WriteCard(nv, 0);
  WriteString(", consonants: ");
  WriteCard(nc, 0);
  WriteString(", other: ");
  WriteCard(i - nv - nc, 0);
  WriteLn
END vowels.

Vowels and Letters are set constants. A character is a vowel if it is in Vowels, and a consonant if it is in Letters but not a vowel. In gm2 15.2 a test with a constant on both sides, such as 'e' IN Vowels, crashes the compiler with an internal error; with a variable on the left, as here, it works.

$ gm2 vowels.mod -o vowels
$ ./vowels
Modula-2 was designed by Niklaus Wirth in 1978.
vowels: 12, consonants: 21, other: 14

Finding a meeting time

The last program looks for an hour when three people are free. Each person's busy hours form a set, and the free hours are what is left of the working day after all of them are removed.

meeting.mod
MODULE meeting;

FROM InOut IMPORT WriteString, WriteLn, WriteCard;

TYPE
  Hour = [8..17];
  Hours = SET OF Hour;

VAR
  busy: ARRAY [1..3] OF Hours;
  free: Hours;
  h: Hour;
  p: CARDINAL;

PROCEDURE WriteHours(s: Hours);
VAR
  hour: Hour;
BEGIN
  FOR hour := MIN(Hour) TO MAX(Hour) DO
    IF hour IN s THEN
      WriteCard(hour, 3)
    END
  END;
  WriteLn
END WriteHours;

BEGIN
  busy[1] := Hours{8, 9, 12, 15..17};
  busy[2] := Hours{10, 12};
  busy[3] := Hours{8, 11, 16};

  free := Hours{MIN(Hour)..MAX(Hour)};
  FOR p := 1 TO 3 DO
    WriteString("person ");
    WriteCard(p, 0);
    WriteString(" is busy at");
    WriteHours(busy[p]);
    free := free - busy[p]
  END;

  WriteString("everybody is free at");
  WriteHours(free);

  WriteString("first common hour:");
  h := MIN(Hour);
  WHILE (h < MAX(Hour)) AND NOT (h IN free) DO
    INC(h)
  END;
  IF h IN free THEN
    WriteCard(h, 3)
  ELSE
    WriteString(" none")
  END;
  WriteLn
END meeting.

Hours is a set over the subrange 8..17, and the busy hours are kept in an array of sets. free starts as the whole day; each person's busy hours are subtracted from it. The WHILE loop then finds the first hour left in the set.

$ gm2 meeting.mod -o meeting
$ ./meeting
person 1 is busy at  8  9 12 15 16 17
person 2 is busy at 10 12
person 3 is busy at  8 11 16
everybody is free at 13 14
first common hour: 13

Next steps

The strings article works with text stored in arrays of characters, and the character handling article uses sets of characters to classify the characters of a text.

Source

The GNU Modula-2 manual

Modula-2 language reference at modula2.org

In this article we have declared set types, added and removed elements with INCL and EXCL, combined sets with union, intersection and difference, compared them, and used sets of numbers, BITSET and sets of characters. The enumerations and subranges article covers the element types, and the data types article introduces BITSET.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Modula-2 tutorials.