How do I display the contents of a set in Pascal?
I am working with simple sets in Pascal and just want to output the contents of the set. Every time I run the code, I get the following error message: 'project1.lpr (17,13) Error: cannot read or write variables of this type'.
here is my code:
program Project1;
{$mode objfpc}{$H+}
uses
sysutils;
type TFriends = (Anne,Bob,Claire,Derek,Edgar,Francy);
type TFriendGroup = Set of TFriends;
Var set1,set2,set3,set4:TFriendGroup; x:integer;
begin
set1:=[Anne,Bob,Claire];
set2:=[Claire,Derek];
set3:=[Derek,Edgar,Francy];
writeln(set1);
readln;
end.
Is there a special method / function for outputting sets?
thank
source to share
You cannot directly display the set as a string becausethere is no type information issued for it. To do this, your collection must be a published property of the class.
Once posted to the class, you can use the TypInfo block to display the set as a string using the SetToString () function . TypInfo is an FPC block that performs all compiler reflection functions.
A short summary of what you are trying to do:
program Project1;
{$mode objfpc}{$H+}
uses
sysutils, typinfo;
type
TFriends = (Anne,Bob,Claire,Derek,Edgar,Francy);
TFriendGroup = Set of TFriends;
TFoo = class
private
fFriends: TFriendGroup;
published
property Friends: TFriendGroup read fFriends write fFriends;
end;
Var
Foo: TFoo;
FriendsAsString: string;
Infs: PTypeInfo;
begin
Foo := TFoo.Create;
Foo.Friends := [Derek, Edgar, Francy];
//
Infs := TypeInfo(Foo.Friends);
FriendsAsString := SetToString(Infs, LongInt(Foo.Friends), true);
//
Foo.Free;
writeln(FriendsAsString);
readln;
end.
This program outputs:
[Derek, Edgar, Francite]
Further:
source to share
Free Pascal allows you to write / writeln () enums without explicit calls to typinfo.
So
{$mode objfpc} // or Delphi, For..in needs Object Pascal dialect iirc.
var Person :TFriends;
for Person in Set1 do
writeln(Person);
works great.
Using WriteStr this can also be written to strings. (writer does write / write functions, but then to string. Originally implemented for ISO / Mac dialects)
source to share