[fpc-pascal] Re: Delphi's anonymous functions in Free Pascal
Juha Manninen
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:
>
> http://www.youtube.com/watch?v=kYUrqdUyEpI
>
:-)
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 :
http://www.hu.freepascal.org/lists/fpc-pascal/2010-January/023755.html
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
parameterized
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:
type
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
threads
or a thread pool, it could then be easily used to take advantage of multiple
processors:
procedure CalculateExpensiveThings;
var
results: array of Integer;
begin
SetLength(results, 100);
ParallelFor(Low(results), High(results),
procedure(i: Integer) // \
begin // \ code block
results[i] := ExpensiveCalculation(i); // / used as parameter
end // /
);
// use results
end;
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
is
with a virtual base class with one or more abstract methods; consider the
TThread class and its abstract Execute method. However, anonymous methods
make
this pattern--parameterizing of algorithms and data structures using
code--far
easier.
Regards,
Juha Manninen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20111020/ba40c754/attachment.html>
More information about the fpc-pascal
mailing list