Skip to content
Sets
step 1/5

Reading — step 1 of 5

Learn

~1 min readPointers and Sets

Pascal has a built-in set type — a compact, type-safe bitset over a small ordinal range.

type
    TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
    TDays = set of TDay;

var
    weekdays: TDays;
begin
    weekdays := [Mon, Tue, Wed, Thu, Fri];

    if Mon in weekdays then
        WriteLn('yes');

    weekdays := weekdays + [Sat];      // add
    weekdays := weekdays - [Mon];      // remove
end.

Set operations:

  • + — union
  • - — difference
  • * — intersection
  • <= — subset
  • >= — superset
  • = — equal
  • in — membership

Sets work on any ordinal type with a small range:

var
    digits: set of '0'..'9';
    primes: set of 1..255;
begin
    digits := ['0', '1', '2', '3'];
    primes := [2, 3, 5, 7, 11, 13];
end.

Pascal sets are bit fields under the hood — extremely fast membership tests. The downside: range can't exceed 256 elements (in standard FPC).

Use cases:

  • Character class checks: if c in ['a'..'z', 'A'..'Z'] then
  • State flags: if optActive in opts then
  • Permission masks

For larger sets (millions of elements), use a TBitSet class or hash-based set from a library.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Sets — Pascal Intermediate