Skip to content

Instantly share code, notes, and snippets.

@chainq
Last active June 1, 2017 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chainq/12761a20d88f995d754b71d6a3127362 to your computer and use it in GitHub Desktop.
Save chainq/12761a20d88f995d754b71d6a3127362 to your computer and use it in GitHub Desktop.
Example about Sets, Enums and Arrays in Pascal (requires Free Pascal 2.4 or newer)
{$MODE OBJFPC}
program MonthsAndSeasons;
uses
sysutils, dateutils;
function hasArguments: boolean;
const
yesNo: array[boolean] of string = ( 'No', 'Yes' );
begin
result:=ParamCount > 0;
writeln('Arguments: ',yesNo[result]);
end;
type
Months = ( January = 1, February, March, April, May, June,
July, August, September, October, November, December );
Seasons = ( Winter, Spring, Summer, Autumn );
MonthsOfSeason = set of Months;
const
{ Enums with explicit value setting cannot be used as index value
in the array declaration, so use low/high approach here }
MonthStrings: array[low(Months)..high(Months)] of string =
( 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December' );
SeasonStrings: array[Seasons] of string =
( 'Winter', 'Spring', 'Summer', 'Autumn' );
const
WinterMonths = [ December, January, February ];
SpringMonths = [ March, April, May ];
SummerMonths = [ June, July, August ];
AutumnMonths = [ September, October, November ];
const
SeasonData: array[Seasons] of MonthsOfSeason =
( WinterMonths, SpringMonths, SummerMonths, AutumnMonths );
HalfsOfYear: array[boolean] of MonthsOfSeason =
( [January..June], [July..December] );
procedure printOutMonthAndSeason(currentMonth: Months);
const
FirstSecond: array[boolean] of string = ( 'first', 'second' );
var
currentSeason: MonthsOfSeason;
s: Seasons;
begin
s:=low(Seasons);
for currentSeason in SeasonData do
begin
if currentMonth in currentSeason then
writeln(MonthStrings[currentMonth],' is during the ',SeasonStrings[s],
' in the ',FirstSecond[currentMonth in HalfsOfYear[true]],' half of the year');
Inc(s);
end;
end;
function getMonthFromDate: Months;
begin
result:=Months(MonthOf(Date));
end;
function getMonth: Months;
var
code: Integer;
begin
if hasArguments then
begin
{ Because result is of "Months" type which is an enum,
thanks to RTTI this will accept also months names as
parameters coming from the command line, and convert
them to the right enum value... }
Val(ParamStr(1), result, code);
if code > 0 then
begin
writeln('That''s not a month.');
result:=getMonthFromDate;
end;
end
else
result:=getMonthFromDate;
end;
begin
printOutMonthAndSeason(getMonth);
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment