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

[{'answer_id': 16504, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 6, 'selected': False, 'text': '<p>It refers to <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="noreferrer">lambda calculus</a>, which is a formal system that just has lambda expressions, which represent a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type, i.e., <code>λ : λ → λ</code>.</p>\n\n<p>Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product:</p>\n\n<pre><code>(lambda (x y) (* x y)) \n</code></pre>\n\n<p>It can be applied in-line like this (evaluates to <em>50</em>):</p>\n\n<pre><code>((lambda (x y) (* x y)) 5 10)\n</code></pre>\n'}, {'answer_id': 16505, 'author': 'mercutio', 'author_id': 1951, 'author_profile': 'https://Stackoverflow.com/users/1951', 'pm_score': 2, 'selected': False, 'text': '<p>You can think of it as an anonymous function - here\'s some more info: <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="nofollow noreferrer">Wikipedia - Anonymous Function</a></p>\n'}, {'answer_id': 16509, 'author': 'mk.', 'author_id': 1797, 'author_profile': 'https://Stackoverflow.com/users/1797', 'pm_score': 11, 'selected': True, 'text': '<p>Lambda comes from the <a href="http://en.wikipedia.org/wiki/Lambda_calculus" rel="noreferrer">Lambda Calculus</a> and refers to anonymous functions in programming.</p>\n\n<p>Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this.</p>\n\n<p><strong>Python</strong></p>\n\n<pre class="lang-py prettyprint-override"><code>def adder(x):\n    return lambda y: x + y\nadd5 = adder(5)\nadd5(1)\n6\n</code></pre>\n\n<p>As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have.</p>\n\n<p><strong>Examples in other languages</strong></p>\n\n<p><strong>Perl 5</strong></p>\n\n<pre class="lang-pl prettyprint-override"><code>sub adder {\n    my ($x) = @_;\n    return sub {\n        my ($y) = @_;\n        $x + $y\n    }\n}\n\nmy $add5 = adder(5);\nprint &amp;$add5(1) == 6 ? "ok\\n" : "not ok\\n";\n</code></pre>\n\n<p><strong>JavaScript</strong></p>\n\n<pre class="lang-js prettyprint-override"><code>var adder = function (x) {\n    return function (y) {\n        return x + y;\n    };\n};\nadd5 = adder(5);\nadd5(1) == 6\n</code></pre>\n\n<p><strong>JavaScript (ES6)</strong></p>\n\n<pre class="lang-js prettyprint-override"><code>const adder = x =&gt; y =&gt; x + y;\nadd5 = adder(5);\nadd5(1) == 6\n</code></pre>\n\n<p><strong>Scheme</strong></p>\n\n<pre class="lang-scheme prettyprint-override"><code>(define adder\n    (lambda (x)\n        (lambda (y)\n           (+ x y))))\n(define add5\n    (adder 5))\n(add5 1)\n6\n</code></pre>\n\n<p><strong><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.110%29.aspx" rel="noreferrer">C# 3.5 or higher</a></strong></p>\n\n<pre class="lang-cs prettyprint-override"><code>Func&lt;int, Func&lt;int, int&gt;&gt; adder = \n    (int x) =&gt; (int y) =&gt; x + y; // `int` declarations optional\nFunc&lt;int, int&gt; add5 = adder(5);\nvar add6 = adder(6); // Using implicit typing\nDebug.Assert(add5(1) == 6);\nDebug.Assert(add6(-1) == 5);\n\n// Closure example\nint yEnclosed = 1;\nFunc&lt;int, int&gt; addWithClosure = \n    (x) =&gt; x + yEnclosed;\nDebug.Assert(addWithClosure(2) == 3);\n</code></pre>\n\n<p><strong>Swift</strong></p>\n\n<pre class="lang-swift prettyprint-override"><code>func adder(x: Int) -&gt; (Int) -&gt; Int{\n   return { y in x + y }\n}\nlet add5 = adder(5)\nadd5(1)\n6\n</code></pre>\n\n<p><strong>PHP</strong></p>\n\n<pre class="lang-php prettyprint-override"><code>$a = 1;\n$b = 2;\n\n$lambda = fn () =&gt; $a + $b;\n\necho $lambda();\n</code></pre>\n\n<p><strong>Haskell</strong></p>\n\n<pre><code>(\\x y -&gt; x + y) \n</code></pre>\n\n<p><strong>Java</strong> see <a href="https://stackoverflow.com/questions/36233477/lambda-expression-in-java-1-8/36233545#36233545">this post</a></p>\n\n<pre class="lang-java prettyprint-override"><code>// The following is an example of Predicate : \n// a functional interface that takes an argument \n// and returns a boolean primitive type.\n\nPredicate&lt;Integer&gt; pred = x -&gt; x % 2 == 0; // Tests if the parameter is even.\nboolean result = pred.test(4); // true\n</code></pre>\n\n<p><strong>Lua</strong></p>\n\n<pre class="lang-lua prettyprint-override"><code>adder = function(x)\n    return function(y)\n        return x + y\n    end\nend\nadd5 = adder(5)\nadd5(1) == 6        -- true\n</code></pre>\n\n<p><strong>Kotlin</strong></p>\n\n<pre class="lang-kotlin prettyprint-override"><code>val pred = { x: Int -&gt; x % 2 == 0 }\nval result = pred(4) // true\n</code></pre>\n\n<p><strong>Ruby</strong></p>\n\n<p>Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas.</p>\n\n<pre class="lang-ruby prettyprint-override"><code>def adder(x)\n  lambda { |y| x + y }\nend\nadd5 = adder(5)\nadd5[1] == 6\n</code></pre>\n\n<p>Ruby being Ruby, there is a shorthand for lambdas, so you can define <code>adder</code> this way:</p>\n\n<pre><code>def adder(x)\n  -&gt; y { x + y }\nend\n</code></pre>\n\n<p><strong>R</strong></p>\n\n\n\n<pre class="lang-r prettyprint-override"><code>adder &lt;- function(x) {\n  function(y) x + y\n}\nadd5 &lt;- adder(5)\nadd5(1)\n#&gt; [1] 6\n</code></pre>\n'}, {'answer_id': 16510, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 7, 'selected': False, 'text': '<p>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.</p>\n\n<p>For instance, here\'s a C# piece of code that doesn\'t use a lambda:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public Int32 Add(Int32 a, Int32 b)\n{\n    return a + b;\n}\n\npublic Int32 Sub(Int32 a, Int32 b)\n{\n    return a - b;\n}\n\npublic delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));\n}\n\npublic void Test()\n{\n    Calculator(10, 23, Add);\n    Calculator(10, 23, Sub);\n}\n</code></pre>\n\n<p>This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.</p>\n\n<p>In C# 2.0 we got anonymous methods, which shortens the above code to:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));\n}\n\npublic void Test()\n{\n    Calculator(10, 23, delegate(Int32 a, Int32 b)\n    {\n        return a + b;\n    });\n    Calculator(10, 23, delegate(Int32 a, Int32 b)\n    {\n        return a - b;\n    });\n}\n</code></pre>\n\n<p>And then in C# 3.0 we got lambdas which makes the code even shorter:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public delegate Int32 Op(Int32 a, Int32 b);\n\npublic void Calculator(Int32 a, Int32 b, Op op)\n{\n    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));\n}\n\npublic void Test()\n{\n    Calculator(10, 23, (a, b) =&gt; a + b);\n    Calculator(10, 23, (a, b) =&gt; a - b);\n}\n</code></pre>\n'}, {'answer_id': 16511, 'author': 'Serhat Ozgel', 'author_id': 31505, 'author_profile': 'https://Stackoverflow.com/users/31505', 'pm_score': 2, 'selected': False, 'text': '<p>It is a function that has no name. For e.g. in c# you can use</p>\n\n<pre><code>numberCollection.GetMatchingItems&lt;int&gt;(number =&gt; number &gt; 5);\n</code></pre>\n\n<p>to return the numbers that are greater than 5.</p>\n\n<pre><code>number =&gt; number &gt; 5\n</code></pre>\n\n<p>is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.</p>\n'}, {'answer_id': 16513, 'author': 'Jon Galloway', 'author_id': 5, 'author_profile': 'https://Stackoverflow.com/users/5', 'pm_score': 3, 'selected': False, 'text': '<p>I like the explanation of Lambdas in this article: <a href="http://msdn.microsoft.com/en-us/magazine/cc163400.aspx" rel="noreferrer">The Evolution Of LINQ And Its Impact On The Design Of C#</a>. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.</p>\n\n<p>Their quick explanation: Lambdas are a way to treat code (functions) as data.</p>\n'}, {'answer_id': 16514, 'author': 'Keith', 'author_id': 905, 'author_profile': 'https://Stackoverflow.com/users/905', 'pm_score': 4, 'selected': False, 'text': "<p>Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.</p>\n\n<p>In C# lambda syntax is often compiled to simple methods in the same way as anonymous delegates, but it can also be broken down and its logic read.</p>\n\n<p>For instance (in C#3):</p>\n\n<pre><code>LinqToSqlContext.Where( \n    row =&gt; row.FieldName &gt; 15 );\n</code></pre>\n\n<p>LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.</p>\n\n<p>The statement above becomes:</p>\n\n<pre><code>select ... from [tablename] \nwhere [FieldName] &gt; 15      --this line was 'read' from the lambda function\n</code></pre>\n\n<p>This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be <em>read</em>.</p>\n\n<p>Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:</p>\n\n<pre><code>LinqToSqlContext.Where( \n    row =&gt; SomeComplexCheck( row.FieldName ) );\n</code></pre>\n\n<p>Now the expression tree cannot be read - SomeComplexCheck cannot be broken down. The SQL statement will execute without the where, and every row in the data will be put through <code>SomeComplexCheck</code>.</p>\n\n<p>Lambda functions should not be confused with anonymous methods. For instance:</p>\n\n<pre><code>LinqToSqlContext.Where( \n    delegate ( DataRow row ) { \n        return row.FieldName &gt; 15; \n    } );\n</code></pre>\n\n<p>This also has an 'inline' function, but this time it's just compiler magic - the C# compiler will split this out to a new instance method with an autogenerated name. </p>\n\n<p>Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.</p>\n"}, {'answer_id': 16578, 'author': 'CodingWithoutComments', 'author_id': 25, 'author_profile': 'https://Stackoverflow.com/users/25', 'pm_score': 3, 'selected': False, 'text': "<p>An example of a lambda in Ruby is as follows:</p>\n\n<pre><code>hello = lambda do\n    puts('Hello')\n    puts('I am inside a proc')\nend\n\nhello.call\n</code></pre>\n\n<p>Will genereate the following output:</p>\n\n<pre><code>Hello\nI am inside a proc\n</code></pre>\n"}, {'answer_id': 16680, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 3, 'selected': False, 'text': '<p>@Brian I use lambdas all the time in C#, in LINQ and non-LINQ operators. Example:</p>\n\n<pre><code>string[] GetCustomerNames(IEnumerable&lt;Customer&gt; customers)\n { return customers.Select(c=&gt;c.Name);\n }\n</code></pre>\n\n<p>Before C#, I used anonymous functions in JavaScript for callbacks to AJAX functions, before the term Ajax was even coined:</p>\n\n<pre><code>getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});\n</code></pre>\n\n<p>The interesting thing with C#\'s lambda syntax, though, is that on their own their type cannot be infered (i.e., you can\'t type var foo = (x,y) => x * y) but depending on which type they\'re assigned to, they\'ll be compiled as delegates or abstract syntax trees representing the expression (which is how LINQ object mappers do their "language-integrated" magic).</p>\n\n<p>Lambdas in LISP can also be passed to a quotation operator and then traversed as a list of lists. Some powerful macros are made this way. </p>\n'}, {'answer_id': 23046, 'author': 'SarekOfVulcan', 'author_id': 2531, 'author_profile': 'https://Stackoverflow.com/users/2531', 'pm_score': 2, 'selected': False, 'text': '<p>I have trouble wrapping my head around lambda expressions because I work in Visual FoxPro, which has Macro substitution and the ExecScript{} and Evaluate() functions, which seem to serve much the same purpose.</p>\n\n<pre><code>? Calculator(10, 23, "a + b")\n? Calculator(10, 23, "a - b");\n\nFUNCTION Calculator(a, b, op)\nRETURN Evaluate(op)\n</code></pre>\n\n<p>One definite benefit to using formal lambdas is (I assume) compile-time checking: Fox won\'t know if you typo the text string above until it tries to run it.</p>\n\n<p>This is also useful for data-driven code: you can store entire routines in memo fields in the database and then just evaluate them at run-time. This lets you tweak part of the application without actually having access to the source. (But that\'s another topic altogether.)</p>\n'}, {'answer_id': 34969, 'author': 'joel.neely', 'author_id': 3525, 'author_profile': 'https://Stackoverflow.com/users/3525', 'pm_score': 6, 'selected': False, 'text': '<p>The name "lambda" is just a historical artifact. All we\'re talking about is an expression whose value is a function.</p>\n\n<p>A simple example (using Scala for the next line) is:</p>\n\n<pre><code>args.foreach(arg =&gt; println(arg))\n</code></pre>\n\n<p>where the argument to the <code>foreach</code> method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you\'ll get the idea):</p>\n\n<pre><code>void printThat(Object that) {\n  println(that)\n}\n...\nargs.foreach(printThat)\n</code></pre>\n\n<p>except that you don\'t need to bother with:</p>\n\n<ol>\n<li>Declaring the function somewhere else (and having to look for it when you revisit the code later).</li>\n<li>Naming something that you\'re only using once.</li>\n</ol>\n\n<p>Once you\'re used to function values, having to do without them seems as silly as being required to name every expression, such as:</p>\n\n<pre><code>int tempVar = 2 * a + b\n...\nprintln(tempVar)\n</code></pre>\n\n<p>instead of just writing the expression where you need it:</p>\n\n<pre><code>println(2 * a + b)\n</code></pre>\n\n<p>The exact notation varies from language to language; Greek isn\'t always required!  ;-)</p>\n'}, {'answer_id': 1254843, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>In Javascript, for example, functions are treated as the same mixed type as everything else (<code>int</code>, <code>string</code>, <code>float</code>, <code>bool</code>). As such, you can create functions on the fly, assign them to things, and call them back later. It\'s useful but, not something you want to over use or you\'ll confuse everyone who has to maintain your code after you...</p>\n\n<p>This is some code I was playing with to see how deep this rabbit hole goes:</p>\n\n<pre class="lang-js prettyprint-override"><code>var x = new Object;\nx.thingy = new Array();\nx.thingy[0] = function(){ return function(){ return function(){ alert(\'index 0 pressed\'); }; }; }\nx.thingy[1] = function(){ return function(){ return function(){ alert(\'index 1 pressed\'); }; }; }\nx.thingy[2] = function(){ return function(){ return function(){ alert(\'index 2 pressed\'); }; }; }\n\nfor(var i=0 ;i&lt;3; i++)\n    x.thingy[i]()()();\n</code></pre>\n'}, {'answer_id': 10807110, 'author': 'learnvst', 'author_id': 276193, 'author_profile': 'https://Stackoverflow.com/users/276193', 'pm_score': 3, 'selected': False, 'text': '<p>Just because I cant see a C++11 example here, I\'ll go ahead and post this nice example from <a href="http://software.intel.com/en-us/blogs/2009/08/03/hello-lambdas-c-0x-a-quick-guide-to-lambdas-in-c/" rel="nofollow noreferrer">here</a>. After searching, it is the clearest language specific example that I could find.</p>\n\n<h1>Hello, Lambdas, version 1</h1>\n\n<pre><code>template&lt;typename F&gt;\n\nvoid Eval( const F&amp; f ) {\n\xa0\xa0\xa0     f();\n}\nvoid foo() {\n\xa0\xa0\xa0     Eval( []{ printf("Hello, Lambdas\\n"); } );\n}\n</code></pre>\n\n<h1>Hello, Lambdas, version 2:</h1>\n\n<pre><code>void bar() {\n\xa0\xa0\xa0 auto f = []{ printf("Hello, Lambdas\\n"); };\n\xa0\xa0\xa0 f();\n}\n</code></pre>\n'}, {'answer_id': 18222531, 'author': 'isomorphismes', 'author_id': 563329, 'author_profile': 'https://Stackoverflow.com/users/563329', 'pm_score': 6, 'selected': False, 'text': '<p>The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example <code>x+y=5</code> paired with <code>x−y=1</code>. Along with ways to manipulate individual equations it\'s also possible to put the information from these two together, provided cross-equation substitutions are done logically. Lambda calculus codifies the correct way to do these substitutions.</p>\n\n<p>Given that <code>y = x−1</code> is a valid rearrangement of the second equation, this: <code>λ y = x−1</code> means a function substituting the symbols <code>x−1</code> for the symbol <code>y</code>. Now imagine applying <code>λ y</code> to each term in the first equation. If a term is <code>y</code> then perform the substitution; otherwise do nothing. If you do this out on paper you\'ll see how applying that <code>λ y</code> will make the first equation solvable.</p>\n\n<p>That\'s an answer without any computer science or programming.</p>\n\n<p>The simplest programming example I can think of comes from <a href="http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works">http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works</a>:</p>\n\n<blockquote>\n  <p>here is how the square function might be defined in an imperative\n  programming language (C):</p>\n\n<pre><code>int square(int x)\n{\n    return x * x;\n}\n</code></pre>\n  \n  <p>The variable x is a formal parameter which is replaced by the actual\n  value to be squared when the function is called. In a functional\n  language (Scheme) the same function would be defined:</p>\n\n<pre><code>(define square\n  (lambda (x) \n    (* x x)))\n</code></pre>\n  \n  <p>This is different in many ways, but it still uses the formal parameter\n  x in the same way.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Added:</strong> <a href="http://imgur.com/a/XBHub">http://imgur.com/a/XBHub</a></p>\n\n<p><a href="http://imgur.com/a/XBHub"><img src="https://i.imgur.com/gbRsoXU.png" alt="lambda"></a></p>\n'}, {'answer_id': 39058940, 'author': 'battlmonstr', 'author_id': 1009546, 'author_profile': 'https://Stackoverflow.com/users/1009546', 'pm_score': 2, 'selected': False, 'text': '<p>In context of CS a lambda function is an abstract mathematical concept that tackles a problem of symbolic evaluation of mathematical expressions. In that context a lambda function is the same as a <a href="https://en.wikipedia.org/wiki/Lambda_calculus#Lambda_terms" rel="nofollow">lambda term</a>.</p>\n\n<p>But in programming languages it\'s something different. It\'s a piece of code that is declared "in place", and that can be passed around as a "first-class citizen". This concept appeared to be useful so that it came into almost all popular modern programming languages (see <a href="http://dobegin.com/lambda-functions-everywhere/" rel="nofollow">lambda functions everwhere</a> post).</p>\n'}, {'answer_id': 41948308, 'author': 'Nick Louloudakis', 'author_id': 2672913, 'author_profile': 'https://Stackoverflow.com/users/2672913', 'pm_score': 4, 'selected': False, 'text': '<p>The question is formally answered greatly, so I will not try to add more on this.</p>\n\n<p>In very simple, <strong>informal</strong> words to someone that knows very little or nothing on math or programming, I would explain it as a small "machine" or "box" that takes some input, makes some work and produces some output, has no particular name, but we know where it is and by just this knowledge, we use it.</p>\n\n<p>Practically speaking, for a person that knows what a function is, I would tell them that it is a function that has no name, usually put to a point in memory that can be used just by referencing to that memory (usually via the usage of a variable - if they have heard about the concept of the function pointers, I would use them as a similar concept) - this answer covers the pretty basics (no mention of closures etc) but one can get the point easily.</p>\n'}, {'answer_id': 45001563, 'author': 'konmik', 'author_id': 3492625, 'author_profile': 'https://Stackoverflow.com/users/3492625', 'pm_score': 2, 'selected': False, 'text': '<p>In computer programming, lambda is a piece of code (statement, expression or a group of them) which takes some arguments from an external source. It must not always be an anonymous function - we have many ways to implement them.</p>\n\n<p>We have clear separation between expressions, statements and functions, which mathematicians do not have.</p>\n\n<p>The word "function" in programming is also different - we have "function is a series of steps to do" (from Latin "perform"). In math it is something about correlation between variables.</p>\n\n<p>Functional languages are trying to be as similar to math formulas as possible, and their words mean almost the same. But in other programming languages we have it different.</p>\n'}, {'answer_id': 47355087, 'author': 'AbstProcDo', 'author_id': 7301792, 'author_profile': 'https://Stackoverflow.com/users/7301792', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>\n</blockquote>\n\n<p>I will illustrate it intuitively step by step in simple and readable python codes.</p>\n\n<p>In short, a lambda is just an anonymous and inline function.</p>\n\n<p>Let\'s start from assignment to understand <code>lambdas</code> as a freshman with background of basic arithmetic.</p>\n\n<p>The blueprint of assignment is \'the name = value\', see:</p>\n\n<pre><code>In [1]: x = 1\n   ...: y = \'value\'\nIn [2]: x\nOut[2]: 1\nIn [3]: y\nOut[3]: \'value\'\n</code></pre>\n\n<p>\'x\', \'y\' are names and 1, \'value\' are values.\nTry a function in mathematics</p>\n\n<pre><code>In [4]: m = n**2 + 2*n + 1\nNameError: name \'n\' is not defined\n</code></pre>\n\n<p>Error reports,<br>\nyou cannot write a mathematic directly as code,\'n\' should be defined or be assigned to a value.</p>\n\n<pre><code>In [8]: n = 3.14\nIn [9]: m = n**2 + 2*n + 1\nIn [10]: m\nOut[10]: 17.1396\n</code></pre>\n\n<p>It works now,what if you insist on combining the two seperarte lines to one.\nThere comes <code>lambda</code></p>\n\n<pre><code>In [13]: j = lambda i: i**2 + 2*i + 1\nIn [14]: j\nOut[14]: &lt;function __main__.&lt;lambda&gt;&gt;\n</code></pre>\n\n<p>No errors reported.</p>\n\n<p>This is a glance at <code>lambda</code>, it enables you to write a function in a single line as you do in mathematic into the computer directly.</p>\n\n<p>We will see it later.</p>\n\n<p>Let\'s continue on digging deeper on \'assignment\'.</p>\n\n<p>As illustrated above, the equals symbol <code>=</code> works for simple data(1 and \'value\') type and simple expression(n**2 + 2*n + 1).</p>\n\n<p>Try this:</p>\n\n<pre><code>In [15]: x = print(\'This is a x\')\nThis is a x\nIn [16]: x\nIn [17]: x = input(\'Enter a x: \')\nEnter a x: x\n</code></pre>\n\n<p>It works for simple statements,there\'s 11 types of them in python <a href="https://docs.python.org/3/reference/simple_stmts.html" rel="nofollow noreferrer">7. Simple statements — Python 3.6.3 documentation</a></p>\n\n<p>How about compound statement,</p>\n\n<pre><code>In [18]: m = n**2 + 2*n + 1 if n &gt; 0\nSyntaxError: invalid syntax\n#or\nIn [19]: m = n**2 + 2*n + 1, if n &gt; 0\nSyntaxError: invalid syntax\n</code></pre>\n\n<p>There comes <code>def</code> enable it working</p>\n\n<pre><code>In [23]: def m(n):\n    ...:     if n &gt; 0:\n    ...:         return n**2 + 2*n + 1\n    ...:\nIn [24]: m(2)\nOut[24]: 9\n</code></pre>\n\n<p>Tada, analyse it, \'m\' is name, \'n**2 + 2*n + 1\' is value.<code>:</code> is a variant of \'=\'.<br>\nFind it, if just for understanding, everything starts from assignment and everything is assignment.</p>\n\n<p>Now return to <code>lambda</code>, we have a function named \'m\' </p>\n\n<p>Try:</p>\n\n<pre><code>In [28]: m = m(3)\nIn [29]: m\nOut[29]: 16\n</code></pre>\n\n<p>There are two names of \'m\' here, function <code>m</code> already has a name, duplicated.</p>\n\n<p>It\'s formatting like:</p>\n\n<pre><code>In [27]: m = def m(n):\n    ...:         if n &gt; 0:\n    ...:             return n**2 + 2*n + 1\n    SyntaxError: invalid syntax\n</code></pre>\n\n<p>It\'s not a smart strategy, so error reports</p>\n\n<p>We have to delete one of them,set a function without a name.</p>\n\n<pre><code>m = lambda n:n**2 + 2*n + 1\n</code></pre>\n\n<p>It\'s called \'anonymous function\'</p>\n\n<p>In conclusion,</p>\n\n<ol>\n<li><code>lambda</code> in an inline function which enable you to write a function in one straight line as does in mathematics</li>\n<li><code>lambda</code> is anonymous</li>\n</ol>\n\n<p>Hope, this helps.</p>\n'}, {'answer_id': 50459728, 'author': 'madeinQuant', 'author_id': 5329711, 'author_profile': 'https://Stackoverflow.com/users/5329711', 'pm_score': 1, 'selected': False, 'text': '<p>The question has been answered fully, I don\'t want to go into details. I want to share the usage when writing numerical computation in rust.</p>\n\n<p>There is an example of a lambda(anonymous function)</p>\n\n<pre><code>let f = |x: f32| -&gt; f32 { x * x - 2.0 };\nlet df = |x: f32| -&gt; f32 { 2.0 * x };\n</code></pre>\n\n<p>When I was writing a module of Newton–Raphson method, it was used as first and second order derivative. (If you want to know what is Newton–Raphson method, please visit "<a href="https://en.wikipedia.org/wiki/Newton%27s_method" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Newton%27s_method</a>". </p>\n\n<p>The output as the following</p>\n\n<pre><code>println!("f={:.6}      df={:.6}", f(10.0), df(10.0))\n\nf=98.000000       df=20.000000\n</code></pre>\n'}, {'answer_id': 52646171, 'author': 'akinov', 'author_id': 6565365, 'author_profile': 'https://Stackoverflow.com/users/6565365', 'pm_score': 1, 'selected': False, 'text': "<p>Imagine that you have a restaurant with a delivery option and you have an order that needs to be done in under 30 minutes. The point is clients usually don't care if you send their food by bike with a car or barefoot as long as you keep the meal warm and tied up. So lets convert this idiom to Javascript with anonymous and defined transportation functions.</p>\n\n<p>Below we defined the way of our delivering aka we define a name to a function:</p>\n\n<pre><code>// ES5 \nvar food = function withBike(kebap, coke) {\nreturn (kebap + coke); \n};\n</code></pre>\n\n<p>What if we would use arrow/lambda functions to accomplish this transfer:</p>\n\n<pre><code>// ES6    \nconst food = (kebap, coke) =&gt; { return kebap + coke };\n</code></pre>\n\n<p>You see there is no difference for client and no time wasting to think about how to send food. Just send it.</p>\n\n<p>Btw, I don't recommend the kebap with coke this is why upper codes will give you errors. Have fun.</p>\n"}, {'answer_id': 54168332, 'author': 'Andy Jazz', 'author_id': 6599590, 'author_profile': 'https://Stackoverflow.com/users/6599590', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n<p>A <code>Lambda Function</code>, or a <code>Small Anonymous Function</code>, is a self-contained block of functionality that can be passed around and used in your code. Lambda has different names in different programming languages – <code>Lambda</code> in <strong>Python</strong> and <strong>Kotlin</strong>, <code>Closure</code> in <strong>Swift</strong>, or <code>Block</code> in <strong>C</strong> and <strong>Objective-C</strong>. Although lambda\'s meaning is quite similar for these languages it has slight distinctions sometimes.</p>\n</blockquote>\n<h2>Let\'s see how Closure (Lambda) works in Swift:</h2>\n<pre class="lang-swift prettyprint-override"><code>let coffee: [String] = [&quot;Cappuccino&quot;, &quot;Espresso&quot;, &quot;Latte&quot;, &quot;Ristretto&quot;]\n</code></pre>\n<h2>1. Regular Function</h2>\n<pre class="lang-swift prettyprint-override"><code>func backward(_ n1: String, _ n2: String) -&gt; Bool {\n    return n1 &gt; n2\n}\nvar reverseOrder = coffee.sorted(by: backward)\n\n\n// RESULT: [&quot;Ristretto&quot;, &quot;Latte&quot;, &quot;Espresso&quot;, &quot;Cappuccino&quot;]\n</code></pre>\n<h2>2. Closure Expression</h2>\n<pre class="lang-swift prettyprint-override"><code>reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -&gt; Bool in   \n    return n1 &gt; n2\n})\n</code></pre>\n<h2>3. Inline Closure Expression</h2>\n<pre class="lang-swift prettyprint-override"><code>reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -&gt; Bool in \n    return n1 &gt; n2 \n})\n</code></pre>\n<h2>4. Inferring Type From Context</h2>\n<pre class="lang-swift prettyprint-override"><code>reverseOrder = coffee.sorted(by: { n1, n2 in return n1 &gt; n2 } )\n</code></pre>\n<h2>5. Implicit Returns from Single-Expression Closures</h2>\n<pre class="lang-swift prettyprint-override"><code>reverseOrder = coffee.sorted(by: { n1, n2 in n1 &gt; n2 } )\n</code></pre>\n<h2>6. Shorthand Argument Names</h2>\n<pre class="lang-swift prettyprint-override"><code>reverseOrder = coffee.sorted(by: { $0 &gt; $1 } )\n\n// $0 and $1 are closure’s first and second String arguments.\n</code></pre>\n<h2>7. Operator Methods</h2>\n<pre class="lang-swift prettyprint-override"><code>reverseOrder = coffee.sorted(by: &gt;)\n\n// RESULT: [&quot;Ristretto&quot;, &quot;Latte&quot;, &quot;Espresso&quot;, &quot;Cappuccino&quot;]\n</code></pre>\n'}, {'answer_id': 62742314, 'author': 'Thingamabobs', 'author_id': 13629335, 'author_profile': 'https://Stackoverflow.com/users/13629335', 'pm_score': 3, 'selected': False, 'text': '<h2><strong>Lambda explained for everyone:</strong></h2>\n<p>Lambda is an anonymous function. This means lambda is a function object in Python that doesn\'t require a reference before. Let\'s consider this bit of code here:</p>\n<pre class="lang-py prettyprint-override"><code>def name_of_func():\n    #command/instruction\n    print(\'hello\')\n\nprint(type(name_of_func))   #the name of the function is a reference\n                            #the reference contains a function Object with command/instruction\n</code></pre>\n<p>To proof my proposition I print out the type of name_of_func which returns us:</p>\n<pre><code>&lt;class \'function\'&gt;\n</code></pre>\n<p>A function must have a interface, but a interface docent needs to contain something. What does this mean? Let\'s look a little bit closer to our function and we may notice that out of the name of the functions there are some more details we need to explain to understand what a function is.</p>\n<p>A regular function will be defined with the syntax <em><strong>&quot;def&quot;</strong></em>, then we type in the name and settle the interface with <em><strong>&quot;()&quot;</strong></em> and ending our definition by the syntax <em><strong>&quot;:&quot;</strong></em>. Now we enter the functions body with our instructions/commands.</p>\n<p>So let\'s consider this bit of code here:</p>\n<pre class="lang-py prettyprint-override"><code>def print_my_argument(x):\n    print(x)\n\n\nprint_my_argument(\'Hello\')\n</code></pre>\n<p>In this case we run our function, named &quot;print_my_argument&quot; and passing a parameter/argument through the interface. The Output will be:</p>\n<pre><code>Hello\n</code></pre>\n<p>So now that we know what a function is and how the architecture works for a function, we can take a look to an anonymous function. Let\'s consider this bit of code here:</p>\n<pre class="lang-py prettyprint-override"><code>def name_of_func():\n    print(\'Hello\')\n\n\n\nlambda: print(\'Hello\')\n</code></pre>\n<p>these function objects are pretty much the same except of the fact that the upper, regular function have a name and the other function is an anonymous one. Let\'s take a closer look on our anonymous function, to understand how to use it.</p>\n<p>So let\'s consider this bit of code here:</p>\n<pre class="lang-py prettyprint-override"><code>def delete_last_char(arg1=None):\n    print(arg1[:-1])\n\nstring = \'Hello World\'\ndelete_last_char(string)\n\nf = lambda arg1=None: print(arg1[:-1])\nf(string)\n</code></pre>\n<p>So what we have done in the above code is to write once again, a regular function and an anonymous function. Our anonymous function we had assigned to a var, which is pretty much the same as to give this function a name. Anyway, the output will be:</p>\n<pre><code>Hello Worl\nHello Worl\n</code></pre>\n<p>To fully proof that lambda is a function object and doesn\'t just mimic a function we run this bit of code here:</p>\n<pre class="lang-py prettyprint-override"><code>string = \'Hello World\'\nf = lambda arg1=string: print(arg1[:-1])\nf()\nprint(type(f))\n</code></pre>\n<p>and the Output will be:</p>\n<pre><code>Hello Worl\n&lt;class \'function\'&gt;\n</code></pre>\n<p>Last but not least you should know that every function in python needs to return something. If nothing is defined in the body of the function, None will be returned by default. look at this bit of code here:</p>\n<pre class="lang-py prettyprint-override"><code>def delete_last_char(arg1):\n    print(arg1[:-1])\n\nstring = \'Hello World\'\nx = delete_last_char(string)\n\nf = lambda arg1=string: print(arg1[:-1])\nx2 = f()\n\nprint(x)\nprint(x2)\n</code></pre>\n<p>Output will be:</p>\n<pre><code>Hello Worl\nHello Worl\nNone\nNone\n</code></pre>\n'}, {'answer_id': 63696082, 'author': 'oluwaferanmi Fakolujo', 'author_id': 14178278, 'author_profile': 'https://Stackoverflow.com/users/14178278', 'pm_score': -1, 'selected': False, 'text': '<p>A lambda function can take any number of arguments, but they contain only a single expression. ...\nLambda functions can be used to return function objects.\nSyntactically, lambda functions are restricted to only a single expression.</p>\n'}]
['https://Stackoverflow.com/questions/16501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1344/']