[fpc-pascal] Help creating generic class: division problem

leledumbo leledumbo_cool at yahoo.co.id
Mon Apr 5 16:04:33 CEST 2010

consider the following generic class declaration:

{$mode objfpc}{$H+}

  generic TMedian<T> = class
    class function Find(x: array of T): T;

class function TMedian.Find(x: array of T): T;
  i, j, Middle: Integer;
  Temporary: T;
  // Use truncated selection sort to find median
  Middle := (High(x) + 1) div 2;
  for i := 0 to Middle do
    for j := 1 to High(x) - i do
      if x[j] > x[j - 1] then begin
        Temporary := x[j];
        x[j] := x[j - 1];
        x[j - 1] := Temporary;
  if Odd(High(x)) then
    // When High(x) is Odd, there are an even number of elements in array.
    // Define median as average of two middle values.
    Result := (x[Middle] + x[Middle - 1]) / 2 // <-- This line
    // When High(x) is Even, there are an odd number of elements in array.
    // Median is the middle value.
    Result := x[Middle];
end {Find};

How can I make it work such that:

  TMedianInteger = specialize TMedian<Integer>;
  TMedianDouble = specialize TMedian<Double>;

is valid?

See the line marked with <-- above, due to semantic of /, I can't use
integer because / returns floating point value, Extended to be precise. If I
change it to div, it won't work (correctly) for floating point values,
because the precision is lost. Typecasting to T won't work either because
Extended can't be converted to LongInt (larger to smaller type problem).

View this message in context: http://old.nabble.com/Help-creating-generic-class%3A-division-problem-tp28140305p28140305.html
Sent from the Free Pascal - General mailing list archive at Nabble.com.

More information about the fpc-pascal mailing list