[fpc-pascal] Feature proposal: function-based assignment operators

Sven Barth pascaldragon at googlemail.com
Thu Mar 28 17:47:32 CET 2013


Am 28.03.2013 16:23, schrieb Benito van der Zander:
> Hi,
> quite often you need to change a value relatively to another value.
> For example:
>
>   array1[array2[i]] := array1[array2[i]] + 42;
>
> Luckily this can be written as
>
>   array1[array2[i]] += 42;
>
> Which is nice.
>
> However, sometimes you do not need addition, but the minimum.
> For example:
>
>    array1[array2[i]] := min(array1[array2[i]], 42);
>
> Now, you need to repeat all the array indices.
>
> Which is very ugly.
>
> So there should be an alternative syntax, similar to += :
> I.e.:
>
>    array1[array2[i]] min= 42;
>
>
> More generally, if func is a 2-ary function, of type type(a) => 
> type(b) => type(a), the syntax
>
> a func= b
>
> should become a := func(a, b)
>
> (Or alternatively the syntax   a : func = b;  might be easier to parse)
>
There was already a discussion some time ago whether we should allow 
operators like "or=" and such as well and the result was simple: no. I 
consider this the same here.

You can achieve a similar effect through type helpers in 2.7.1 though:

=== code begin ===

program mintest;

{$mode objfpc}

uses
   Math;

type
   TLongIntHelper = type helper for LongInt
     procedure Min(aValue: LongInt);
   end;

procedure TLongIntHelper.Min(aValue: LongInt);
begin
   Self := Math.Min(Self, aValue);
end;

var
   arr: array[0..20] of LongInt;
   i: LongInt;
begin
   for i := Low(arr) to High(arr) do
     arr[i] := i;

   for i := Low(arr) to High(arr) do
     Write(arr[i], ' ');
   Writeln;

   arr[15].Min(10); // arr[15] is passed as Self to Min

   for i := Low(arr) to High(arr) do
     Write(arr[i], ' ');
   Writeln;
end.

=== code end ===

Regards,
Sven



More information about the fpc-pascal mailing list