alias vs enum for lambdas?

Paul Backus snarwin at gmail.com
Thu May 1 15:31:32 UTC 2025


On Monday, 28 April 2025 at 04:59:24 UTC, Orion wrote:
> At the compiler level, enum lambda is represented as a literal.
> But how is alias represented? As an expression?

A lambda is basically syntax sugar for a local function 
declaration. So when you write this:

     fun((float x) => 0.5 + x);

...the compiler replaces it internally with code that looks like 
this:

     auto __lambda(float x) => 0.5 + x;
     fun(&__lambda);

When the lambda is generic, the compiler generates a template 
function instead of a regular function:

     // Before:
     range.map!(x => 0.5 + x);

     // After:
     auto __lambda(T)(T x) => 0.5 + x;
     range.map!(__lambda);

So, when you use `alias` to give a name to a lambda, what you are 
really doing is giving a name to this internal function or 
template that the compiler replaces the lambda with.

Of course, at that point, you might as well just write a named 
function directly:

     // Instead of this:
     alias m = (float x) => 0.5 + x;

     // You can just write this:
     auto m(float x) => 0.5 + x;


More information about the Digitalmars-d-learn mailing list