This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.
Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.
Project: Array Utilities Unit
Unit: DelphiDabbler.Lib.ArrayUtils
Record: TArrayUtils
Applies to: ~>0.1
type
TReducer<TIn,TOut> = reference to function (const AAccumulator: TOut;
const ACurrent: TIn): TOut;
TReducerEx<TIn,TOut> = reference to function (const AAccumulator: TOut;
const ACurrent: TIn; const AIndex: Integer;
const AArray: array of TIn): TOut;
class function Reduce<TIn,TOut>(const A: array of TIn;
const AReducer: TReducer<TIn,TOut>; const AInitialValue: TOut): TOut;
overload; static;
class function Reduce<TIn,TOut>(const A: array of TIn;
const AReducer: TReducerEx<TIn,TOut>; const AInitialValue: TOut): TOut;
overload; static;
Reduces the elements of an array to a single value of an optionally different type to that of the array elements.
Parameters:
A - The array whose elements are to be reduced.
AReducer - Callback function executed for each element in the array that is used to calculate the reduced value. AReducer must be a function of type TReducer<TIn,TOut> or TReducerEx<TIn,TOut>.
Parameter(s):
0
. (TReducerEx<TIn,TOut> only.)Returns:
AInitialValue - A value, of type TOut, to which AAccumulator is initialized the first time that AReducer is called.
Returns:
This first example uses the first overload of Reduce<Tin,TOut> that uses a callback of type TReducer<TIn,TOut>. The procedure counts the number of strings in an array that begin with given text.
procedure Reduce_TwoTypes_Eg1;
const
RequiredStr = 'needle';
var
A: TArray<string>;
CountStrsReducer: TArrayUtils.TReducer<string,Integer>;
begin
CountStrsReducer := function (const AAccumulator: Integer;
const ACurrent: string): Integer
begin
Result := AAccumulator;
if Pos(RequiredStr, ACurrent) = 1 then
Inc(Result);
end;
A := TArray<string>.Create('find', 'the', 'needle', 'and', 'more', 'needles');
Assert(TArrayUtils.Reduce<string,Integer>(A, CountStrsReducer, 0) = 2);
end;
This second example uses the second overload of Reduce<Tin,TOut> that uses a callback of type TReducerEx<TIn,TOut>. The calculates the arithmetic mean of a list of integers stored in an array.
procedure Reduce_TwoTypes_Eg2;
var
AverageReducer: TArrayUtils.TReducerEx<Integer,Extended>;
A: TArray<Integer>;
begin
AverageReducer := function (const AAccumulator: Extended;
const ACurrent: Integer; const AIndex: Integer;
const AArray: array of Integer): Extended
begin
// Don't call with empty array
Result := AAccumulator + ACurrent / Length(A);
end;
A := TArray<Integer>.Create(3, 6, 3, 8, 3, 2);
Assert(
SameValue(
4.16666666666667,
TArrayUtils.Reduce<Integer,Extended>(A, AverageReducer, 0),
0.000001
)
);
end;