Updates to Modern Object Pascal Introduction - anonymous functions, generic collections sorting

VS Code with Pascal example of anonymous functions

We have updated our Modern Object Pascal Introduction for Programmers. Enjoy!

The most important addition is the section about “Anonymous functions”. It’s mostly just a simple example (tested to compile with both FPC and Delphi) along with links to good Delphi and FPC documentation. The examples are also in the repository:

The above examples probably do not really do “justice” to demonstrate anonymous functions capabilities. The big thing is that, as you can write the body of anonymous function inside a larger context, you can access the variables from that context. This means that there’s less need to invent “how to pass additional data to a callback”, which is a common need when using normal callbacks (to global routines or methods) that requires adding new fields or even classes that are useful only temporarily. Various details of this mechanism are documented in Delphi documentation (and the FPC implementation is compatible, from what I know).

While we cannot use the anonymous functions in CGE code (as we want to stay compatible with FPC >= 3.2.0, while anonymous functions are only in unstable FPC 3.3.1 for now). But there’s no reason why you couldn’t use them in your own projects, if you use Delphi or FPC 3.3.1. To install FPC 3.3.1 we recommend FpcUpDeluxe. In the CGE editor preferences, you can point to the FPC version you’d like to use, choosing any installation done by FpcUpDeluxe.

Another update is fix to Generics.Collections example showcasing sorting using custom comparer. Recent FPC versions change the required parameter type from constref to const (for Delphi compatibility as well as better code generation).

We have also updated the scripts of modern-pascal-introduction to ease updating everything when the content changes, and defined GitHub Actions to check that all code samples build correctly.

1 Like