DMarlon Studio

Lesson 17 · 17 of 20

Enumerated types and sets · Pascal

Define enumerated types and sets in Pascal: a shop's opening days with in, Include, Exclude, Ord, Succ and set intersection.

Pascal · Enumerated types and sets in DMarlon Studio: the example's code and its output in the terminal

An enumerated type is an ordered list of names: TDay = (Mon, Tue, ...). It is clearer than using numbers for days, and the compiler will not let you mix it up with other types. Free Pascal prints its name with WriteLn: Wed.

Each value has a position, starting at 0: `Ord(Wed)` is 2. `Succ` gives the next one and `Pred` the previous one. Because they are ordinal, they work as a for counter and as case options.

A set (set of TDay) holds some of those values, with no order and no repeats. [Mon..Fri] are the working days; `Include` adds Saturday and `Exclude` removes Wednesday. `in` asks whether a value is in the set: Sun in open is FALSE.

Sets have operators: + is union, - difference and * intersection. open * [Sat, Sun] gives the weekend days the shop opens, and `for ... in` goes through them one by one.

Sets of Char are handy for classifying characters: c in ['a', 'e', 'i', 'o', 'u'] tells you whether c is a vowel. for c in also walks through a string letter by letter.

Code · main.pas

program main;type  TDay = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);  // an enumerated type  TDays = set of TDay;var  day: TDay;  open: TDays;  c: Char;  vowels: Integer;begin  day := Wed;  WriteLn(day, ' is at position ', Ord(day), '; the next day is ', Succ(day));  // A set holds some of those values, without order or repeats.  open := [Mon..Fri];  Include(open, Sat);  Exclude(open, Wed);  for day := Mon to Sun do    if day in open then      Write(day, ' ');  WriteLn;  WriteLn('Open on Sunday? ', Sun in open);  for day in open * [Sat, Sun] do  // * is the intersection    WriteLn('Open at the weekend: ', day);  // Sets of Char make quick character tests.  vowels := 0;  for c in 'free pascal compiler' do    if c in ['a', 'e', 'i', 'o', 'u'] then      Inc(vowels);  WriteLn('Vowels: ', vowels);end.

Output · fpc main.pas && ./main

Wed is at position 2; the next day is Thu
Mon Tue Thu Fri Sat 
Open on Sunday? FALSE
Open at the weekend: Sat
Vowels: 7

Key points

  • (A, B, C) defines an enumerated type.
  • Ord, Succ and Pred give the position, the next and the previous value.
  • set of T holds values with no order or repeats.
  • in, Include, Exclude, +, - and * work on sets.

Exercise

Create a TTopping = (Cheese, Ham, Mushrooms, Olives, Pepper) type and a set with the toppings on a pizza; print the ones it has and, with -, the ones it is missing to have them all.