What is a lambda and what is an example implementation?

后端 未结 6 877
轮回少年
轮回少年 2020-12-30 15:43

I am fairly new to programming and while doing a lot of reading this concept of a lambda keeps coming up but I\'m having a hard time putting my finger on what it actually is

6条回答
  •  温柔的废话
    2020-12-30 16:22

    lambda in the programming world means an anonymous function that can be passed and returned like every other normal variable. So-called functional languages have them builtin but recently there is a growing set of languages supporting them, since they allow writing reusable code. See this for example, written in the next version of C++:

    // write this once...
    int transform_values(int * values, int n, function f) {
        for(int i = 0; i < n; i++)
            values[i] = f(values[i]);
    }
    
    int values[] = { 1, 2, 3, 4 };
    // ... then call it to double the values in an array
    transform_values(values, 4, [](int v) { return v * 2; });
    

    It does look similar in C# and other languages supporting lambdas. Now there is the word "closure". It means that a lambda can capture local variables and use them in the computation of its result:

    int local_variable = 5;
    int values[] = { 1, 2, 3, 4 };
    // ... then call it to multiply the values in an array
    transform_values(values, 4, [=](int v) { return v * local_variable; });
    

    The variable local_variable is now captured inside the closure and can be used within it. Variables may also be updated by a closure. Lambdas are a basic building block of functional languages. Here is an example in haskell:

    map (\x -> x * 2) [1, 2, 3, 4]
    

    Will do the same as the C++ code above. It maps the values in the list using the given function (a lambda here) into a result list. Using haskell, you can see nicely how the syntax used maps to the mathematical notion of Lambda Calculus.

提交回复
热议问题