[fpc-pascal] Feature announcement: Dynamic array extensions
Anthony Walter
sysrpl at gmail.com
Fri May 25 01:06:32 CEST 2018
I just wanted to drop this trick to work around problems with record
helpers ..
If you wanted to create a record helper for a type that is not normally
allowed, or perhaps you want to have multiple record helpers for the same
type, consider defining your own separate type and make it contain said
type with implicit conversions to work around those problem.
Example:
TArray<T> = array of T;
TArrayList<T> = record
public
{ The array acting as a list }
var Items: TArray<T>;
{ Convert an array to a list }
class operator Implicit(const Value: TArray<T>): TArrayList<T>;
{ Convert an open array to a list }
class operator Implicit(const Value: array of T): TArrayList<T>;
{ Convert a list to an array }
class operator Implicit(const Value: TArrayList<T>): TArray<T>;
Then in this example you can add all the methods you want to dynamic
arrays, because you have your own type which is nothing more than an alias
to a dynamic array (array of T). Methods such as:
{ Performs a simple safe copy of up to N elements }
procedure Copy(out List: TArrayList<T>; N: Integer);
{ Performs a fast unsafe copy of up to N elements }
procedure CopyFast(out List: TArrayList<T>; N: Integer);
{ Returns the lower bounds of the list }
function Lo: Integer;
{ Returns the upper bounds of the list }
function Hi: Integer;
{ Reverses the items in the list }
procedure Reverse;
{ Swap two items in the list }
procedure Exchange(A, B: Integer);
{ Adds and item to the end of the list }
procedure Push(const Item: T);
{ Appends an array of items to the list }
procedure PushRange(const Collection: array of T);
{ Remove an item from the end of the list }
function Pop: T;
{ Remove an item randomly from the list }
function PopRandom: T;
{ Return a copy of the list with items passing through a filter }
function Filter(Func: TFilterFunc<T>): TArrayList<T>;
{ Resurn the first item matching a condition }
function FirstOf(Func: TFilterFunc<T>): T;
{ Removes an item by index from the list and decresaes the count by one }
procedure Delete(Index: Integer);
{ Removes all items setting the count of the list to 0 }
procedure Clear;
{ Sort the items using a comparer }
procedure Sort(Order: TSortingOrder = soAscend; Comparer: TCompare<T> =
nil);
{ Attempt to find the item using DefaultCompare }
function IndexOf(const Item: T): Integer; overload;
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20180524/90e7acd0/attachment.html>
More information about the fpc-pascal
mailing list