[fpc-pascal] Re: Delphi's anonymous functions in Free Pascal

Andrew Pennebaker andrew.pennebaker at gmail.com
Wed Oct 19 20:23:56 CEST 2011


Practical uses for referencable anonymous functions:

(map f collection)

This is the prototypical way to run a function over each element in a
collection, returning the results.

Example:

(map (lambda (x) (+ x 1)) '(1 2 3))

-> (2 3 4)

(sort compare collection)

When dealing with complex data types, the user may want to implement a
custom compare function.

(sort (lambda (x y) (- y:employee-id x:employeeid)) (list emp1 emp2 emp3))

-> (emp3 emp1 emp2)

(zip f collection1 collection2)

Similar to map, zip runs a 2-input function over the elements of the
collections, returning the results.

(zip (lamba (x y) (+ x y)) '(1 2 3) '(4 5 6))

-> (5 7 9)

At first glance, each of these examples may seem pointless. Can't we
implement the same behavior without referencing anonymous functions? Yes, we
can, but only for a specific function. If you want your database library to
allow users to customize sorting, you'll need referencable anonymous
functions.

If you've used a functional language, you know how powerful these little
functions are, and you'll miss them and want to implement them in languages
that don't have them.

Cheers,

Andrew Pennebaker
www.yellosoft.us

On Wed, Oct 19, 2011 at 2:04 PM, Florian Klämpfl <florian at freepascal.org>wrote:

> Am 19.10.2011 10:16, schrieb Sven Barth:
> > Am 19.10.2011 09:31, schrieb Michael Fuchs:
> >> I would prefer a style like
> >>
> >> myfunc := @function(x, y: Integer): Integer Result := x + y;
> >
> > And how would you create more complex functions? In Pascal code blocks
> > are started with "begin" and ended with "end". I don't see a reason why
> > anonymous methods should differ here.
> >
> > Also the example given by Embarcadero is a bit boring. The interesting
> > thing about anonymous methods (and nested functions types in FPC) is
> > that they can access variables of the surrounding function (at least I
> > hope that I've understand it correctly that nested function types can do
> > that).
>
>
> The main difference between anonymous methods and nested functions is
> that one can return a reference to an anonymous method from a function,
> the anonymous method can access local variables from that function and
> even after exiting the function, the variables are still valid. This
> means that local variables accessed in a anonymous method end up on the
> heap.
>
> However, I fail to see reasonable use cases for anonymous methods
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20111019/0192faa0/attachment.html>


More information about the fpc-pascal mailing list