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 and how implementing it will make my programming life so much better. So first, what is a lambda and second how might it be implemented?
Thanks to all who posted. As has been mentioned in the comments, this is a duplicate, but there are so many great answers here I want to preserve them for the community so I’m turning it into a community post. Here is the link to the other question:
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 :
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 :
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 :
In Javascript, you usually pass a function to others functions. Example with JQuery :
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.