[fpc-pascal] Re: Delphi's anonymous functions in Free Pascal
juha.manninen62 at gmail.com
Thu Oct 20 22:31:16 CEST 2011
2011/10/20 Florian Klämpfl <florian at freepascal.org>
> If anybody does not see why increasing complexity without a good reason
> should be avoided, I recommend:
There is lots of confusion about anonymous functions. The name is
misleading, they are called closures in other languages.
There was a similar discussion earlier, see :
The origin is from functional languages but it is fine to borrow it to OP,
the same way classes and object features were borrowed earlier from other
languages. Besides I think the closure addition is almost as important.
They have some very important uses, like making multithreading easier.
I copy text from Delphi help page again here because it looks so cool:
Using Code for a Parameter
Anonymous methods make it easier to write functions and structures
by code, not just values.
Multithreading is a good application for anonymous methods. if you
want to execute
some code in parallel,
you might have a parallel-for function that looks like this:
TProcOfInteger = reference to procedure(x: Integer);
procedure ParallelFor(start, finish: Integer; proc: TProcOfInteger);
The ParallelFor procedure iterates a procedure over different threads.
Assuming this procedure is implemented correctly and efficiently using
or a thread pool, it could then be easily used to take advantage of multiple
results: array of Integer;
procedure(i: Integer) // \
begin // \ code block
results[i] := ExpensiveCalculation(i); // / used as parameter
end // /
// use results
Contrast this to how it would need to be done without anonymous methods:
probably a "task" class with a virtual abstract method, with a concrete
descendant for ExpensiveCalculation, and then adding all the tasks to a
queue--not nearly as natural or integrated.
Here, the "parallel-for" algorithm is the abstraction that is being
parameterized by code. In the past, a common way to implement this pattern
with a virtual base class with one or more abstract methods; consider the
TThread class and its abstract Execute method. However, anonymous methods
this pattern--parameterizing of algorithms and data structures using
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the fpc-pascal