[fpc-pascal] Feature announcement: implicit generic function specializations
Hairy Pixels
genericptr at gmail.com
Mon Apr 25 05:15:26 CEST 2022
> On Apr 23, 2022, at 9:09 PM, Hairy Pixels <genericptr at gmail.com> wrote:
>
> The two languages I use commonly these days are Swift and C#, both of which do implicit function specialization by default. After you use a generic function a couple times it becomes apparent the compiler could infer the types and it’s less code to write so it’s natural that any language that has generic functions would support this feature.
I was thinking about this more and I actually feel like we got this backwards in Pascal and the default should be implicit specialization with manual specialization being a fallback for more challenging cases.
If you have a function:
generic function Add<T>(left, right: T): T;
And the programmer intends to call it like:
Add(1,1);
or
var
a, b: Integer;
begin
Add(a, b);
Why should the programmer need to tell the compiler it’s dealing with Integer when it’s so obvious from the types being used? All the programmer should know is that there is type “T” and any type will work (I know, we don’t have type constraints for built-in types and yes, we should implement that).
For the case of types I understand we must specialize because we’re creating a new type each time and there is nothing to infer from the context, but for functions it’s backwards, that is we know the types being used, we just need to choose the right function based on those types.
If it’s ever allowed to do generic type helpers (I would like do this also) I think the same idea applies. Manually specializing the type doesn’t provide any better control then allowing the compiler to specialize based on the type being extended.
type
generic TArrayHelper<T> = type helper for array of T
procedure Add(value: T);
end;
var
a: array of integer;
begin
a.Add(1); // specialize TArrayHelper<Integer> since the compiler clearly knows the type used is Integer.
end.
Regards,
Ryan Joseph
More information about the fpc-pascal
mailing list