It is hard to catch a lambda, but once you have portrayed them, you cannot understand why you did not do this before.
Lamdba - Anonymous Functions
Lambda are ordinary functions, the only difference is that you are not giving them a name.
To understand this, you must first know that when creating a function, the code is stored in memory at an address known only to the computer.
So, when you do something like this:
function Foo () { }
What you really do is bind the name "Foo" to the code address in memory.
Now there is another way to access the address: links (and pointers, but skip these nasty guys)
Well, a lambda function is a function that has no name, so access can only be with its link.
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:
- Create function
- Get the link
- Pass the link somewhere, it will be used
Finally, the link is lost, and therefore the function is automatically destroyed.
A typical use case is a callback function. You declare, create and pass a function in one line, therefore it is convenient.
Real word example
In Python, you can use lambda in lists:
function_list = [(lambda x : number_to_add + x) for number_to_add in range(0, 10) ]
In Javascript, you usually pass a function to other functions. JQuery example:
$("img").each( function(i){ his.src = "test" i ".jpg"; } );
What you better know
Some languages, such as Javascript or Lisp, make extensive use of lambdas. It may be culturally reasonable, but the functional programming paradigm tends to lead to lambda mania.
Long lambdas make code difficult to read. This is why some languages limit the capabilities of lambdas, such as Python, which prevent them from claiming "if".
Lambda is just normal functions. Wherever you use, you can use the regular function. This is just a coding style question.