Comment by StilesCrisis

9 hours ago

I wish the readme example showed a lambda capture. Now that's where compiler magic REALLY shows up.

C++ lambdas are just structs that overload operator(); once you realize that they become a lot less mysterious. But it's a great example of how this tool is useful to learn about those things (of course you could also read the C++ standard but who has time for that?)

Here's an example: https://cppinsights.io/s/f04b6896

(That also shows how C++'s range-based for-loops work, which is similarly some syntactic suger for a fairly mundane for-loop, but details are interesting: unlike a typical for-loop, the loop variable is declared inside the loop body.)

  • I said shows a lambda _capture_. This involves the compiler automatically determining which variables cross the scope boundary, and injecting code for each one.

Lambdas in D are just nested functions:

    int foo(int i) {
        int add(int x) { return i + x; } // nested function
        return add(3);
    }

    int bar(int i {
        alias lambda = (x) => x + i;  // lambda
        return lambda(3);
    }
    }