[fpc-devel] Functors

Martin Frb lazarus at mfriebe.de
Mon Dec 27 01:14:54 CET 2021

On 27/12/2021 00:18, Blaise at blaise.ru wrote:
> On 27.12.2021 0:57, Martin Frb via fpc-devel wrote:
>>>     writeln( aC(33) );
>>>     aC('hello');
>> the above examples are probably intended to show the syntax. But not 
>> indented to show any useful application?
> The test you quoted demonstrates what is already possible, 
> syntactically and semantically, using a simple patch I have extracted 
> from my implementation of Closures.

No judgment, but just checking if I missed anything... From the above 
examples, it then is a shortcut?

"shortcut" in the sense that it enables you to skip writing the name of 
the method that is called?
"shortcut" in the sense, that anything you can do with it, you can 
already do without it (and without changing the structure of your code, 
or adding massive amounts of code)?

This is what irritates me, if this is a feature, it should enable me to 
do something that otherwise would have been at least some little bit 
more complex.

Functor and class are (as I understand you) equal in:
- you need to create / destroy them.
- you can store data / add (none default) methods
But different in (and only in?), that a functor has a default method.

Your way to describe it "it can be passed as a function" or "behaves 
like a routine" does not add anything new.
A method / method-reference can do exactly all of that.

As I write this I feel, that I really must be missing some point... I 
just don't see where.
(Sorry for the very repetitive questioning about / just wanted to make 
sure I highlight every angle of my current understanding)

>> a functor is meant to be ref-counted
> A functor is a non-routine entity ("object") that behaves like a 
> routine. Meaning: you can invoke it like a routine (via an overloaded 
> "operator ()"), you can store it like a routine (in a method pointer). 
> That is all, it is quite a simple feature, really. RECORD, OBJECT, 
> CLASS, and INTERFACE instances are supported as such entities. With 
> these entities, you manage memory as usual.

So basically

   TInvoke = procedure of object;

TFunctor = class
   procedure Invoke;

operator := (a: TFunctor): TInvoke;
   result := TInvoke(@a.Invoke);

- I don't need to write the operator by hand, and therefore do not need 
to update the name "invoke" if I change it in the class?
- the above only works in assignments, *not* for directly calling 
"MyFunctor();" (which is where it is a shortcut, to leave out the method 

More information about the fpc-devel mailing list