What is a lambda (function)?

后端 未结 23 2285
太阳男子
太阳男子 2020-11-22 04:47

For a person without a comp-sci background, what is a lambda in the world of Computer Science?

相关标签:
23条回答
  • 2020-11-22 05:10

    The question is formally answered greatly, so I will not try to add more on this.

    In very simple, informal words to someone that knows very little or nothing on math or programming, I would explain it as a small "machine" or "box" that takes some input, makes some work and produces some output, has no particular name, but we know where it is and by just this knowledge, we use it.

    Practically speaking, for a person that knows what a function is, I would tell them that it is a function that has no name, usually put to a point in memory that can be used just by referencing to that memory (usually via the usage of a variable - if they have heard about the concept of the function pointers, I would use them as a similar concept) - this answer covers the pretty basics (no mention of closures etc) but one can get the point easily.

    0 讨论(0)
  • 2020-11-22 05:11

    Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.

    Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.

    Python

    def adder(x):
        return lambda y: x + y
    add5 = adder(5)
    add5(1)
    6
    

    As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.

    Examples in other languages

    Perl 5

    sub adder {
        my ($x) = @_;
        return sub {
            my ($y) = @_;
            $x + $y
        }
    }
    
    my $add5 = adder(5);
    print &$add5(1) == 6 ? "ok\n" : "not ok\n";
    

    JavaScript

    var adder = function (x) {
        return function (y) {
            return x + y;
        };
    };
    add5 = adder(5);
    add5(1) == 6
    

    JavaScript (ES6)

    const adder = x => y => x + y;
    add5 = adder(5);
    add5(1) == 6
    

    Scheme

    (define adder
        (lambda (x)
            (lambda (y)
               (+ x y))))
    (define add5
        (adder 5))
    (add5 1)
    6
    

    C# 3.5 or higher

    Func<int, Func<int, int>> adder = 
        (int x) => (int y) => x + y; // `int` declarations optional
    Func<int, int> add5 = adder(5);
    var add6 = adder(6); // Using implicit typing
    Debug.Assert(add5(1) == 6);
    Debug.Assert(add6(-1) == 5);
    
    // Closure example
    int yEnclosed = 1;
    Func<int, int> addWithClosure = 
        (x) => x + yEnclosed;
    Debug.Assert(addWithClosure(2) == 3);
    

    Swift

    func adder(x: Int) -> (Int) -> Int{
       return { y in x + y }
    }
    let add5 = adder(5)
    add5(1)
    6
    

    PHP

    $a = 1;
    $b = 2;
    
    $lambda = fn () => $a + $b;
    
    echo $lambda();
    

    Haskell

    (\x y -> x + y) 
    

    Java see this post

    // The following is an example of Predicate : 
    // a functional interface that takes an argument 
    // and returns a boolean primitive type.
    
    Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.
    boolean result = pred.test(4); // true
    

    Lua

    adder = function(x)
        return function(y)
            return x + y
        end
    end
    add5 = adder(5)
    add5(1) == 6        -- true
    

    Kotlin

    val pred = { x: Int -> x % 2 == 0 }
    val result = pred(4) // true
    

    Ruby

    Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.

    def adder(x)
      lambda { |y| x + y }
    end
    add5 = adder(5)
    add5[1] == 6
    

    Ruby being Ruby, there is a shorthand for lambdas, so you can define adder this way:

    def adder(x)
      -> y { x + y }
    end
    

    R

    adder <- function(x) {
      function(y) x + y
    }
    add5 <- adder(5)
    add5(1)
    #> [1] 6
    
    0 讨论(0)
  • 2020-11-22 05:12

    In computer programming, lambda is a piece of code (statement, expression or a group of them) which takes some arguments from an external source. It must not always be an anonymous function - we have many ways to implement them.

    We have clear separation between expressions, statements and functions, which mathematicians do not have.

    The word "function" in programming is also different - we have "function is a series of steps to do" (from Latin "perform"). In math it is something about correlation between variables.

    Functional languages are trying to be as similar to math formulas as possible, and their words mean almost the same. But in other programming languages we have it different.

    0 讨论(0)
  • 2020-11-22 05:13

    The question has been answered fully, I don't want to go into details. I want to share the usage when writing numerical computation in rust.

    There is an example of a lambda(anonymous function)

    let f = |x: f32| -> f32 { x * x - 2.0 };
    let df = |x: f32| -> f32 { 2.0 * x };
    

    When I was writing a module of Newton–Raphson method, it was used as first and second order derivative. (If you want to know what is Newton–Raphson method, please visit "https://en.wikipedia.org/wiki/Newton%27s_method".

    The output as the following

    println!("f={:.6}      df={:.6}", f(10.0), df(10.0))
    
    f=98.000000       df=20.000000
    
    0 讨论(0)
  • 2020-11-22 05:14

    The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.

    A simple example (using Scala for the next line) is:

    args.foreach(arg => println(arg))
    

    where the argument to the foreach method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):

    void printThat(Object that) {
      println(that)
    }
    ...
    args.foreach(printThat)
    

    except that you don't need to bother with:

    1. Declaring the function somewhere else (and having to look for it when you revisit the code later).
    2. Naming something that you're only using once.

    Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:

    int tempVar = 2 * a + b
    ...
    println(tempVar)
    

    instead of just writing the expression where you need it:

    println(2 * a + b)
    

    The exact notation varies from language to language; Greek isn't always required! ;-)

    0 讨论(0)
  • 2020-11-22 05:17

    Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.

    In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.

    For instance (in C#3):

    LinqToSqlContext.Where( 
        row => row.FieldName > 15 );
    

    LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.

    The statement above becomes:

    select ... from [tablename] 
    where [FieldName] > 15      --this line was 'read' from the lambda function
    

    This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be read.

    Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:

    LinqToSqlContext.Where( 
        row => SomeComplexCheck( row.FieldName ) );
    

    Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through SomeComplexCheck.

    Lambda functions should not be confused with anonymous methods. For instance:

    LinqToSqlContext.Where( 
        delegate ( DataRow row ) { 
            return row.FieldName > 15; 
        } );
    

    This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name.

    Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.

    0 讨论(0)
提交回复
热议问题