What is a lambda and what is an example implementation?

后端 未结 6 860
轮回少年
轮回少年 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:25

    Lambda are hard to catch, but once you have pictured them, you cannot understand why you didn't get it before.

    Lamdba are anonymous functions

    Lambda are ordinary functions, the only difference is that you don't give them a name.

    To understand that, you must know first that when you create a function, the code is stored in memory at an address only knowned by the computer.

    So when you do something like that :

    function Foo ()
    {
     /* your code here */
    }
    

    What you really do is binding the name "Foo" to the adress of the code in memory.

    Now, there is an other way to access an address : references (and pointers, but let's skip this nasty guys)

    Well, a lambda function is a function that have no name, so it can be only access with its reference.

    How do you use them ?

    When you create a lambda function, you usually plan to use it only once.

    The step by step process is usually :

    1. Create the function
    2. Get the reference
    3. Pass the reference somewhere it will be used

    Finally, the reference is lost, and so the function is destroyed automatically.

    The typical use case is a callback function. You declare, create and pass the function in one row, so it's handy.

    Example from the real word

    In Python, you can use lambda in list comprehensions :

    /* create a list of functions */
    function_list = [(lambda x : number_to_add + x) for number_to_add in range(0, 10) ]
    

    In Javascript, you usually pass a function to others functions. Example with JQuery :

     $("img").each(
    
     /* here we pass a function without any name to the "each()" method   */
    
     function(i){  his.src = "test"   i   ".jpg"; }
    
     );
    

    The things you'd better know

    • Some languages, like Javascript or Lisp, make a massive use of lambdas. It can be for cultural reason, but the functional programming paradigm tends to lead to lambda-mania.

    • Long lambdas make the code hard to read. That's why some languages restrain the possibilities of lambdas, such as Python that does not allow "if" statement in them.

    • Lambdas are just normal functions. Where ever you use one, you can use an ordinary function instead. It's just a matter of coding style.

提交回复
热议问题