Corrected the code. I would like to add some helper methods like Contains.
Here's an example using a generic function, the example needs
trunk, though.
I think this is a different but short and elegant approach.
{$mode objfpc}{$modeswitch ImplicitFunctionSpecialization}
{ does not need any units }
generic function Contains<T>(arr: specialize Tarray<T>;value: T): Boolean;
var
e:T;
begin
Result := false;
for e in arr do
if e = value then
begin
result :=true;
break;
end;
end;
var
a:specialize TArray<integer> = (1,2,3,5,6,7,8,9);
begin
writeln(Contains(a,4)); // prints false. implicit specialization
writeln(Contains(a,7)); // prints true;
end.
You can declare generic procedures, functions, methods on any T or TArray<T>.
(generic operators do not work yet, generic functions were introduced in 3.2.0 and implicit specialization in trunk)
In mode delphi it looks like this, but note Delphi does not support implicit specialization, so you can not use this technique in both Delphi and FPC. I just add it because it is an even more compact syntax:
{$mode delphi}{$modeswitch ImplicitFunctionSpecialization}
{ does not need any units }
function Contains<T>(arr:Tarray<T>;value: T): Boolean;inline;
var
e:T;
begin
Result := false;
for e in arr do
if e = value then
begin
result :=true;
break;
end;
end;
var
a:TArray<single> = [1,2,3,5,6,7,8,9];
s:TArray<string> = ['test','me'];
begin
{ implicit specializations }
writeln(Contains(a,4));//false
writeln(Contains(a,7));//true
writeln(Contains(s,'whatever'));// false
writeln(Contains(s,'me')); // true
end.