Search code examples
d

Lambda capture by value in D language


In C++ I can create two lambda each of which captures by value the value of a at the time the lambda was defined.

int main()
{
    int a;

    a = 4;
    auto f1 = [=](int x) { return x * a; };

    a = 6;
    auto f2 = [=](int x) { return x * a; };

    std::cout << "Answer 1 is " << f1(10) << "\n";
    std::cout << "Answer 2 is " << f2(10) << "\n";
}

Result of running is:

Answer 1 is 40
Answer 2 is 60

However in D all I seem to be able to do is this:

import std.stdio;

void main()
{
    int a;

    a = 4;
    auto f1 = (int x){ return x * a;};

    a = 6;
    auto f2 = (int x){ return x * a;};

    writeln("Answer 1 is ", f1(10));
    writeln("Answer 2 is ", f2(10));
}

Which produces the output:

Answer 1 is 60
Answer 2 is 60

Is there any way/syntax to capture the values by value in D similar to using [=] in C++, I can't seem to find an answer in the manual so if there is a way a link would be appreciated to so that I can understand what I missed.


Solution

  • You can 'capture' the multiplier value if you are using a helper function:

    auto multiplier(int m) {
        return (int x){ return x * m;};
    }
    
    void main()
    {
        int a;
    
        a = 4;
        auto f1 = multiplier(a);
    
        a = 6;
        auto f2 = multiplier(a);
    
        writeln("Answer 1 is ", f1(10));
        writeln("Answer 2 is ", f2(10));
    }