Lambda Expressions

后端 未结 4 1154
攒了一身酷
攒了一身酷 2021-02-14 01:45

Can somebody explain me lambda expressions & what they can be used for. I have googled for it & have a rough idea. most of the examples give c# code. How about lambda ex

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 02:04

    el.pescado's answer is right but the example that he provides has an easy work around, using a function pointer. Many uses of lambda functions can't be solved with c's function pointers.

    Say you write these functions in c:

    int Multiply_1(int x) { return(x*1); }
    int Multiply_2(int x) { return(x*2); }
    int Multiply_3(int x) { return(x*3); }
    int Multiply_4(int x) { return(x*4); }
    etcetera, to infinity
    

    Those are all pretty easy to understand. Now assume that you want to write a function that takes y as input and returns a pointer to the function Multiply_y():

    (int)(int) *Make_Multiplier(int y) { return(Multiply_y); }
    

    Where "Multiply_y" is a dynamically created function of the form of Multiply_1, Multiply_2, etc. Languages that have first-class lambda functions can do that.

提交回复
热议问题