locked
nested Lambda RRS feed

  • Question

  • Hi Igor, Mike and everybody
    I am learning Lambda from the documentation.
    I can do the following:
     auto f=[](int x){return x+10;};
            cout <<f(5)<<"\n";//Prints '15'
    What about the folowing one?:
            auto addtwointegers=[](int x){return
                       [=](int y){return x+y;};};
            cout<<addtwointegers(1,2)<<"\n";//Invalid?
     cout<<addtwointegers(2)<<"\n";//Valid? How?

    I have copied and pasted the following program from a website.
    Please have a look and help me please.
    ***************************************************
    #include "stdafx.h"
    #include <iostream>
    #include <functional>

    int main()
    {
        using namespace std;

        // The following code declares a lambda expression that returns
        // another lambda expression that adds two numbers.
        // The returned lambda expression captures parameter x by value.
    [line 10] auto addtwointegers = [](int x) -> function<int(int)> {
            return [=](int y) { return x + y; };
        };

        // The following code declares a lambda expression that takes another
        // lambda expression as its argument.
        // The lambda expression applies the argument z to the function f
        // and multiplies by 2.
        auto higherorder = [](const function<int(int)>& f, int z) {
            return f(z) * 2;
        };

        // Call the lambda expression that is bound to higherorder.
    [line 20] auto answer = higherorder(addtwointegers(7), 8);

        // Print the result, which is (7+8)*2.
        cout << answer << endl;
    }
    +++++++++++++++++++++++++++++++++++++++++++++
    I can't understand [line 20] where addtwointegers takes one parameter.
    In [line 10], there are two paramters for it. Where has (7+8) come
    from?

    Thanks
    Chong

    Wednesday, July 30, 2014 3:10 AM

Answers

  • addtwointegers is a function factory. It takes an integer and manufactures another function - one that returns a sum of this integer and its parameter. In other words, "auto add42 = addtwointegers(42);" is equivalent to "auto add42 = [](int x) { return x + 42; };"

    Another example: "int sum = addtwointegers(7)(8);" (after that, sum == 15). addtwointegers(7) produces a function that takes one parameter and returns this parameter plus 7. This (unnamed) function is immediately called, with 8 as its parameter; it then returns 7 + 8 == 15.


    Igor Tandetnik

    Wednesday, July 30, 2014 4:31 AM