Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a set type as an array index?

I cannot use a set type as an size indicator for an array, however doing so for small sets is perfectly sensible.

Suppose I have the following code:

  TFutureCoreSet = set of 0..15;
  TLookupTable = record
    FData: array[TFutureCoreSet] of TSomeRecord; //error ordinal type required
  ....

The following code compiles and works.

  TFutureCoreSet = set of 0..15;
  TLookupTable = record
    FData: array[word] of TSomeRecord;

This however breaks the link between the allowed number of states in TFutureCoreSet and the elements in the lookup table.
Is there a simple way to link the two so when one changes the other updates as well?

like image 360
Johan Avatar asked Sep 07 '17 14:09

Johan


People also ask

What datatype is array index?

An array is an indexed collection of component variables, called the elements of the array. The indexes are the values of an ordinal type, called the index type of the array.

What type is array index in TypeScript?

The Array. indexOf() is an inbuilt TypeScript function which is used to find the index of the first occurrence of the search element provided as the argument to the function.

Can array index be a variable?

A great use of for loops is performing operations on elements in an array variable. The for loop can increment through the array's index values to access each element of the array in succesion.

Can an array index be a string?

Actually, it has very much to do with the question (specifically, yes, you CAN use a string as an index, but not in the obvious way that the original querier wants).


1 Answers

Just do it slightly differently:

type
  TFutureCore = 0..15;
  TFutureCoreSet = set of TFutureCore;
  TFutureCoreIndex = 0..(2 shl High(TFutureCore)) - 1;
  TLookupTable = record
    FData: array[TFutureCoreIndex] of TSomeRecord;
  end;

The other advantage of using a TFutureCoreIndex is that you can use it to typecast TFutureCoreSet to an ordinal type. When typecasting a set type you must cast to an ordinal type of the same size.

AllowedStates = LookupTable.FData[TFutureCoreIndex(FutureCores)]; //works
AllowedStates = LookupTable.FData[Integer(FutureCores)]; //invalid typecast
AllowedStates = LookupTable.FData[Word(FutureCores)]; //works, but not type safe.
like image 86
Uwe Raabe Avatar answered Oct 28 '22 17:10

Uwe Raabe