For a person without a comp-sci background, what is a lambda in the world of Computer Science?
This question is related to
lambda
language-agnostic
computer-science
terminology
theory
The question is formally answered greatly, so I will not try to add more on this.
In very simple, informal 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.
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.
Slightly oversimplified: a lambda function is one that can be passed round to other functions and it's logic accessed.
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.
For instance (in C#3):
LinqToSqlContext.Where(
row => row.FieldName > 15 );
LinqToSql can read that function (x > 15) and convert it to the actual SQL to execute using expression trees.
The statement above becomes:
select ... from [tablename]
where [FieldName] > 15 --this line was 'read' from the lambda function
This is different from normal methods or anonymous delegates (which are just compiler magic really) because they cannot be read.
Not all methods in C# that use lambda syntax can be compiled to expression trees (i.e. actual lambda functions). For instance:
LinqToSqlContext.Where(
row => SomeComplexCheck( row.FieldName ) );
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 SomeComplexCheck
.
Lambda functions should not be confused with anonymous methods. For instance:
LinqToSqlContext.Where(
delegate ( DataRow row ) {
return row.FieldName > 15;
} );
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.
Anonymous methods can't be read, and so the logic can't be translated out as it can for lambda functions.
I like the explanation of Lambdas in this article: The Evolution Of LINQ And Its Impact On The Design Of C#. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example.
Their quick explanation: Lambdas are a way to treat code (functions) as data.
The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.
A simple example (using Scala for the next line) is:
args.foreach(arg => println(arg))
where the argument to the foreach
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):
void printThat(Object that) {
println(that)
}
...
args.foreach(printThat)
except that you don't need to bother with:
Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:
int tempVar = 2 * a + b
...
println(tempVar)
instead of just writing the expression where you need it:
println(2 * a + b)
The exact notation varies from language to language; Greek isn't always required! ;-)
@Brian I use lambdas all the time in C#, in LINQ and non-LINQ operators. Example:
string[] GetCustomerNames(IEnumerable<Customer> customers)
{ return customers.Select(c=>c.Name);
}
Before C#, I used anonymous functions in JavaScript for callbacks to AJAX functions, before the term Ajax was even coined:
getXmlFromServer(function(result) {/*success*/}, function(error){/*fail*/});
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).
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.
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.
? Calculator(10, 23, "a + b")
? Calculator(10, 23, "a - b");
FUNCTION Calculator(a, b, op)
RETURN Evaluate(op)
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.
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.)
The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example x+y=5
paired with x-y=1
. 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.
Given that y = x-1
is a valid rearrangement of the second equation, this: ? y = x-1
means a function substituting the symbols x-1
for the symbol y
. Now imagine applying ? y
to each term in the first equation. If a term is y
then perform the substitution; otherwise do nothing. If you do this out on paper you'll see how applying that ? y
will make the first equation solvable.
That's an answer without any computer science or programming.
The simplest programming example I can think of comes from http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works:
here is how the square function might be defined in an imperative programming language (C):
int square(int x) { return x * x; }
The variable x is a formal parameter which is replaced by the actual value to be squared when the function is called. In a functional language (Scheme) the same function would be defined:
(define square (lambda (x) (* x x)))
This is different in many ways, but it still uses the formal parameter x in the same way.
Added: http://imgur.com/a/XBHub
In Javascript, for example, functions are treated as the same mixed type as everything else (int
, string
, float
, bool
). 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...
This is some code I was playing with to see how deep this rabbit hole goes:
var x = new Object;
x.thingy = new Array();
x.thingy[0] = function(){ return function(){ return function(){ alert('index 0 pressed'); }; }; }
x.thingy[1] = function(){ return function(){ return function(){ alert('index 1 pressed'); }; }; }
x.thingy[2] = function(){ return function(){ return function(){ alert('index 2 pressed'); }; }; }
for(var i=0 ;i<3; i++)
x.thingy[i]()()();
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.
For instance, here's a C# piece of code that doesn't use a lambda:
public Int32 Add(Int32 a, Int32 b)
{
return a + b;
}
public Int32 Sub(Int32 a, Int32 b)
{
return a - b;
}
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op)
{
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}
public void Test()
{
Calculator(10, 23, Add);
Calculator(10, 23, Sub);
}
This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.
In C# 2.0 we got anonymous methods, which shortens the above code to:
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op)
{
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}
public void Test()
{
Calculator(10, 23, delegate(Int32 a, Int32 b)
{
return a + b;
});
Calculator(10, 23, delegate(Int32 a, Int32 b)
{
return a - b;
});
}
And then in C# 3.0 we got lambdas which makes the code even shorter:
public delegate Int32 Op(Int32 a, Int32 b);
public void Calculator(Int32 a, Int32 b, Op op)
{
Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}
public void Test()
{
Calculator(10, 23, (a, b) => a + b);
Calculator(10, 23, (a, b) => a - b);
}
A lambda function can take any number of arguments, but they contain only a single expression. ... Lambda functions can be used to return function objects. Syntactically, lambda functions are restricted to only a single expression.
You can think of it as an anonymous function - here's some more info: Wikipedia - Anonymous Function
It refers to lambda calculus, 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., ? : ? ? ?
.
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:
(lambda (x y) (* x y))
It can be applied in-line like this (evaluates to 50):
((lambda (x y) (* x y)) 5 10)
A
Lambda Function
, or aSmall Anonymous Function
, 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 –Lambda
in Python and Kotlin,Closure
in Swift, orBlock
in C and Objective-C. Although lambda's meaning is quite similar for these languages it has slight distinctions sometimes.
let coffee: [String] = ["Cappuccino", "Espresso", "Latte", "Ristretto"]
func backward(_ n1: String, _ n2: String) -> Bool {
return n1 > n2
}
var reverseOrder = coffee.sorted(by: backward)
// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]
reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in
return n1 > n2
})
reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in return n1 > n2 } )
reverseOrder = coffee.sorted(by: { n1, n2 in return n1 > n2 } )
reverseOrder = coffee.sorted(by: { n1, n2 in n1 > n2 } )
reverseOrder = coffee.sorted(by: { $0 > $1 } )
// $0 and $1 are closure’s first and second String arguments.
reverseOrder = coffee.sorted(by: >)
// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]
Hope this helps.
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.
We have clear separation between expressions, statements and functions, which mathematicians do not have.
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.
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.
An example of a lambda in Ruby is as follows:
hello = lambda do
puts('Hello')
puts('I am inside a proc')
end
hello.call
Will genereate the following output:
Hello
I am inside a proc
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 lambda term.
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 lambda functions everwhere post).
It is a function that has no name. For e.g. in c# you can use
numberCollection.GetMatchingItems<int>(number => number > 5);
to return the numbers that are greater than 5.
number => number > 5
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.
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.
There is an example of a lambda(anonymous function)
let f = |x: f32| -> f32 { x * x - 2.0 };
let df = |x: f32| -> f32 { 2.0 * x };
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 "https://en.wikipedia.org/wiki/Newton%27s_method".
The output as the following
println!("f={:.6} df={:.6}", f(10.0), df(10.0))
f=98.000000 df=20.000000
Just because I cant see a C++11 example here, I'll go ahead and post this nice example from here. After searching, it is the clearest language specific example that I could find.
template<typename F>
void Eval( const F& f ) {
f();
}
void foo() {
Eval( []{ printf("Hello, Lambdas\n"); } );
}
void bar() {
auto f = []{ printf("Hello, Lambdas\n"); };
f();
}
For a person without a comp-sci background, what is a lambda in the world of Computer Science?
I will illustrate it intuitively step by step in simple and readable python codes.
In short, a lambda is just an anonymous and inline function.
Let's start from assignment to understand lambdas
as a freshman with background of basic arithmetic.
The blueprint of assignment is 'the name = value', see:
In [1]: x = 1
...: y = 'value'
In [2]: x
Out[2]: 1
In [3]: y
Out[3]: 'value'
'x', 'y' are names and 1, 'value' are values. Try a function in mathematics
In [4]: m = n**2 + 2*n + 1
NameError: name 'n' is not defined
Error reports,
you cannot write a mathematic directly as code,'n' should be defined or be assigned to a value.
In [8]: n = 3.14
In [9]: m = n**2 + 2*n + 1
In [10]: m
Out[10]: 17.1396
It works now,what if you insist on combining the two seperarte lines to one.
There comes lambda
In [13]: j = lambda i: i**2 + 2*i + 1
In [14]: j
Out[14]: <function __main__.<lambda>>
No errors reported.
This is a glance at lambda
, it enables you to write a function in a single line as you do in mathematic into the computer directly.
We will see it later.
Let's continue on digging deeper on 'assignment'.
As illustrated above, the equals symbol =
works for simple data(1 and 'value') type and simple expression(n**2 + 2*n + 1).
Try this:
In [15]: x = print('This is a x')
This is a x
In [16]: x
In [17]: x = input('Enter a x: ')
Enter a x: x
It works for simple statements,there's 11 types of them in python 7. Simple statements — Python 3.6.3 documentation
How about compound statement,
In [18]: m = n**2 + 2*n + 1 if n > 0
SyntaxError: invalid syntax
#or
In [19]: m = n**2 + 2*n + 1, if n > 0
SyntaxError: invalid syntax
There comes def
enable it working
In [23]: def m(n):
...: if n > 0:
...: return n**2 + 2*n + 1
...:
In [24]: m(2)
Out[24]: 9
Tada, analyse it, 'm' is name, 'n**2 + 2*n + 1' is value.:
is a variant of '='.
Find it, if just for understanding, everything starts from assignment and everything is assignment.
Now return to lambda
, we have a function named 'm'
Try:
In [28]: m = m(3)
In [29]: m
Out[29]: 16
There are two names of 'm' here, function m
already has a name, duplicated.
It's formatting like:
In [27]: m = def m(n):
...: if n > 0:
...: return n**2 + 2*n + 1
SyntaxError: invalid syntax
It's not a smart strategy, so error reports
We have to delete one of them,set a function without a name.
m = lambda n:n**2 + 2*n + 1
It's called 'anonymous function'
In conclusion,
lambda
in an inline function which enable you to write a function in one straight line as does in mathematicslambda
is anonymousHope, this helps.
Lambda is an annonymous function. This means lambda is a function objekt in Python that doesnt require a reference before. Let's concider this bit of code here:
def name_of_func():
#command/instruction
print('hello')
print(type(name_of_func)) #the name of the function is a reference
#the reference contains a function Objekt with command/instruction
To proof my proposition I print out the type of name_of_func which returns us:
<class 'function'>
A function must have a interface, but a interface dosent 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.
A regular function will be defined with the syntax "def", then we type in the name and settle the interface with "()" and ending our definition by the syntax ":". Now we enter the functions body with our instructions/commands.
So let's consider this bit of code here:
def print_my_argument(x):
print(x)
print_my_argument('Hello')
In this case we run our function, named "print_my_argument" and passing a parameter/argument through the interface. The Output will be:
Hello
So now that we know what a function is and how the architecture works for a function, we can take a look to an annonymous function. Let's consicder this bit of code here:
def name_of_func():
print('Hello')
lambda: print('Hello')
these function objekts are pretty much the same except of the fact that the upper, regular function have a name and the other function is an annonymous one. Let's take a closer look on our annonymous function, to understand how to use it.
So let's concider this bit of code here:
def delete_last_char(arg1=None):
print(arg1[:-1])
string = 'Hello World'
delete_last_char(string)
f = lambda arg1=None: print(arg1[:-1])
f(string)
So what we have done in the above code is to write once againg, a regular function and an anonymous function. Our anonymous function we had assignd to a var, which is pretty much the same as to give this function a name. Anyway, the output will be:
Hello Worl
Hello Worl
To fully proof that lambda is a function object and doesnt just mimik a function we run this bit of code here:
string = 'Hello World'
f = lambda arg1=string: print(arg1[:-1])
f()
print(type(f))
and the Output will be:
Hello Worl
<class 'function'>
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:
def delete_last_char(arg1):
print(arg1[:-1])
string = 'Hello World'
x = delete_last_char(string)
f = lambda arg1=string: print(arg1[:-1])
x2 = f()
print(x)
print(x2)
Output will be:
Hello Worl
Hello Worl
None
None
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.
Below we defined the way of our delivering aka we define a name to a function:
// ES5
var food = function withBike(kebap, coke) {
return (kebap + coke);
};
What if we would use arrow/lambda functions to accomplish this transfer:
// ES6
const food = (kebap, coke) => { return kebap + coke };
You see there is no difference for client and no time wasting to think about how to send food. Just send it.
Btw, I don't recommend the kebap with coke this is why upper codes will give you errors. Have fun.
Source: Stackoverflow.com