Generics

Can Island compile these examples that work in FPC or Delphi? Thank.

program FPC;

{$MODE DELPHI}

procedure QuickSort<T>(const A: ^T; L, R: T);
begin
  if L < R then
  WriteLn('comparison L < R');
end;

begin
end.



program Delphi;

uses
  System.SysUtils;

type
  TArray<T> = record
    procedure QuickSort(const A: TArray<T>; L, R: T);
  end;

procedure TArray<T>.QuickSort(const A: TArray<T>; L, R: T);
begin
  case GetTypeKind(T) of
    tkInteger: WriteLn('Using type Integer');
    tkString: Writeln('Using type String');
  end;
end;

begin
end.

You can use something like

namespace ConsoleApplication4;

interface

type
  TArray<T> = record 
  public
    procedure QuickSort(const A: TArray<T>; L, R: T);
  end;

implementation

method TArray<T>.QuickSort(const A: TArray<T>; L: T; R: T);
begin
  if typeof(T) = typeof(Integer) then
    WriteLn('Using type Integer')
  else if typeof(T) = typeof(string) then
    Writeln('Using type String');
end;

end.

Won’t this produce unnecessary slow code?

In optimized mode it will get rid of the branches that can’t be hit.

1 Like

Ah yes Island is multi-stage compiler so of course it would optimize this… :smiley: