Advertisement
sglienke

Generic number math without generics

May 23rd, 2015
315
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. program GenericMath;
  2.  
  3. {$APPTYPE CONSOLE}
  4.  
  5. uses
  6.   SysUtils;
  7.  
  8. procedure AddInt32(const arr: TArray<Integer>; index: Integer; var result: UInt64);
  9. begin
  10.   Inc(result, arr[index]);
  11. end;
  12.  
  13. procedure AddUInt32(const arr: TArray<Cardinal>; index: Integer; var result: UInt64);
  14. begin
  15.   Inc(result, arr[index]);
  16. end;
  17.  
  18. procedure AddExtended(const arr: TArray<Extended>; index: Integer; var result: Extended);
  19. begin
  20.   result := result + arr[index];
  21. end;
  22.  
  23. procedure SumArray(const arr: Pointer; addProc: Pointer; var result); //inline;
  24. type
  25.   TAddProc = procedure(const arr; index: Integer; var result);
  26. var
  27.   i: Integer;
  28. begin
  29.   for i := 0 to High(TArray<Byte>(arr)) do
  30.     TAddProc(addProc)(arr^, i, result);
  31. end;
  32.  
  33. function Sum(const arr: TArray<Integer>): UInt64; overload; inline;
  34. begin
  35.   Result := 0;
  36.   SumArray(arr, @AddInt32, Result);
  37. end;
  38.  
  39. function Sum(const arr: TArray<Cardinal>): UInt64; overload;
  40. begin
  41.   Result := 0;
  42.   SumArray(arr, @AddUInt32, Result);
  43. end;
  44.  
  45. function Sum(const arr: TArray<Extended>): Extended; overload;
  46. begin
  47.   Result := 0;
  48.   SumArray(arr, @AddExtended, Result);
  49. end;
  50.  
  51. var
  52.   arr1: TArray<Integer>;
  53.   arr2: TArray<Extended>;
  54.   sum1: Integer;
  55.   sum2: Extended;
  56. begin
  57.   arr1 := TArray<Integer>.Create(1, 2, 3, 4, 5, 6, 7, 8, 9);
  58.   arr2 := TArray<Extended>.Create(1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9);
  59.   sum1 := Sum(arr1);
  60.   sum2 := Sum(arr2);
  61.   Writeln(sum1);
  62.   Writeln(sum2);
  63.   Readln;
  64. end.
Advertisement
RAW Paste Data Copied
Advertisement