What is a lambda (function)?

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

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

23条回答
  •  萌比男神i
    2020-11-22 05:10

    A lambda is a type of function, defined inline. Along with a lambda you also usually have some kind of variable type that can hold a reference to a function, lambda or otherwise.

    For instance, here's a C# piece of code that doesn't use a lambda:

    public Int32 Add(Int32 a, Int32 b)
    {
        return a + b;
    }
    
    public Int32 Sub(Int32 a, Int32 b)
    {
        return a - b;
    }
    
    public delegate Int32 Op(Int32 a, Int32 b);
    
    public void Calculator(Int32 a, Int32 b, Op op)
    {
        Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
    }
    
    public void Test()
    {
        Calculator(10, 23, Add);
        Calculator(10, 23, Sub);
    }
    

    This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.

    In C# 2.0 we got anonymous methods, which shortens the above code to:

    public delegate Int32 Op(Int32 a, Int32 b);
    
    public void Calculator(Int32 a, Int32 b, Op op)
    {
        Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
    }
    
    public void Test()
    {
        Calculator(10, 23, delegate(Int32 a, Int32 b)
        {
            return a + b;
        });
        Calculator(10, 23, delegate(Int32 a, Int32 b)
        {
            return a - b;
        });
    }
    

    And then in C# 3.0 we got lambdas which makes the code even shorter:

    public delegate Int32 Op(Int32 a, Int32 b);
    
    public void Calculator(Int32 a, Int32 b, Op op)
    {
        Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
    }
    
    public void Test()
    {
        Calculator(10, 23, (a, b) => a + b);
        Calculator(10, 23, (a, b) => a - b);
    }
    

提交回复
热议问题