Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Delphi type for 'set of integer'?

Tags:

types

delphi

I have several hardcoded validations like these:

const
  cLstAct      =  1;   
  cLstOrg      =  4;
  cLstClockAct = 11;
const
  FUNCT_1 = 224;
  FUNCT_2 = 127;
  FUNCT_3 =   3;

if lFuncID in [FUNCT_1,FUNCT_2,FUNCT_3] then ...
if not (lListType in [cLstAct..cLstOrg,cLstClockAct]) then ...
if not (lPurpose in [0..2]) then ...

that I want to replace with a common method like

function ValidateInSet(AIntValue: integer; AIntSet: @@@): Boolean;
begin
  Result := (AIntValue in AIntSet);
  if not Result then ...
end;  

but what type to choose for AIntSet?

Currently the values to be tested throughout the code go up to a const value 232 (so I can e.g. use a TByteSet = Set of Byte), but I can foresee that we will bump into the E1012 Constant expression violates subrange bounds when the constant values exceed 255.

My Google-fu fails me here...

(Currently on Delphi Seattle Update 1)

like image 620
Jan Doggen Avatar asked Apr 22 '16 10:04

Jan Doggen


1 Answers

Use a dictionary, TDictionary<Integer, Integer>. The value is irrelevant and you only care about the key. If the dictionary contains a specific key then that key is a member of the set. Use AddOrSetValue to add a member, Remove to delete a member and ContainsKey to test membership.

The point of using a dictionary is that it gives you O(1) lookup.

You don't want to use this type directly as a set. You should wrap it in a class that just exposes set like capabilities. An example of that can be found here: https://stackoverflow.com/a/33530037/505088

like image 136
David Heffernan Avatar answered Oct 05 '22 12:10

David Heffernan