Recent

Author Topic: Sets - shorter expression  (Read 9177 times)

BeniBela

  • Hero Member
  • *****
  • Posts: 683
    • homepage
Re: Sets - shorter expression
« Reply #15 on: May 10, 2014, 03:16:22 pm »

But in either case: the whole PByte casting stuff, does not do either of that, or does it?

It does, if you put it in a function

And you only need a single function, not a new one for every set-of-type

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 5695
    • wiki
Re: Sets - shorter expression
« Reply #16 on: May 10, 2014, 03:25:40 pm »
Here is an Operator based approach. Makes only sense, if you have lots of operations on the same type....

Code: [Select]
program Project1;
type
  TOption = (oOne, oTwo, oThree);
  TOptions = set of TOption;

  TOptionModifier = record
    opt:TOption;
    act: Boolean;
  end;

operator * (a: TOption; b: Boolean) c:TOptionModifier;
begin
  c.opt := a;
  c.act := b;
end;

operator + (a: TOptions; b:TOptionModifier) c:TOptions;
begin
  if b.act
  then c := a + [b.opt]
  else c := a - [b.opt];
end;

var options: TOptions;

begin
  Options:=[];
  Options:=Options+oThree*True;
  writeln(oThree in options);
  Options:=Options+oThree*False;
  writeln(oThree in options);
end.

Martin_fr

  • Administrator
  • Hero Member
  • *
  • Posts: 5695
    • wiki
Re: Sets - shorter expression
« Reply #17 on: May 10, 2014, 03:33:46 pm »
It does, if you put it in a function

And you only need a single function, not a new one for every set-of-type
[/quote]

To make it ONE function, you need either untyped params, or call it with Foo(@Options, ord(OThree).

Either will remove type checking (one of the advantages of pascal), and allow you to specify a enum that does not belong to the same type as used for the set.
Then you may as well choose a language that has no type checking to begin with.

It also will not work, if "Options" is a property. No function will (unless it is a published property, and  RTTI is used (specifying property as string/name))