[fpc-pascal] newbie questions
Howard Page-Clark
hdpc at talktalk.net
Tue Apr 20 01:01:59 CEST 2010
> Does this mean that to be able to define a literal value like "byteset := [0, 3, 101]"
>for a set (and probably for an array) I must have defined a custom
type for it; correct?
> (It's the only difference I see with my trials: numbers in my code is
not of a custom type but simply a var of type "Set of Integer".)
> What I mean is, if the value is a literal, instead of only declaring the var then defining its value, one must first make a custom type for it? I don't understand the need& purpose of custom types except for records& enums; but this may be caused by the fact I come from dynamic languages.
>
Yes, you have to use the "typeName = set of .." type declaration to
introduce sets.
You can't have a "set of integer" because that would have more than 256
elements, and in FP (and Delphi I think) the implementation of sets is
limited by that storage constraint.
Custom set types are often used in Pascal to enable meaningful names to
be used for bitmapped values that would otherwise be hard-to-interpret
numbers. For instance, the styles of the Font class are defined thus:
TFontStyle = (fsBold, fsItalic, fsStrikeOut, fsUnderline);
TFontStyles = set of TFontStyle;
If a font is both bold and italic its Style property will have the
numerical value 3. However it is difficult to figure out what "3" means
as a combination of styles. To express it as a combination of named set
elements "fsBold" and "fsItalic" is self-explanatory - the very reason
most of us prefer Pascal to many other languages.
Drop a TButton on a blank form of a new project. Add typinfo to the uses
clause, and put this code in the OnClick event of the button.
procedure TForm1.Button1Click(Sender: TObject);
var styleset: TFontStyles;
b: byte absolute styleset;
begin
if Font.Style = [] then
Font.Style:= Font.Style + [fsBold] + [fsItalic];
styleset := Font.Style;
ShowMessage(Format('Font.Style has the value "[%s]" or, as a numerical
value "%d"',
[SetToString( FindPropInfo(Font, 'style'), integer(Font.Style) ), b ]
) );
end;
See how the numerical value of Font.Style is not very useful?
More information about the fpc-pascal
mailing list