Question

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

Was it helpful?

Solution

Lambda comes from the Lambda Calculus and refers to anonymous functions in programming.

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.

Python

def adder(x):
    return lambda y: x + y
add5 = adder(5)
add5(1)
6

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.

Examples in other languages

Perl 5

sub adder {
    my ($x) = @_;
    return sub {
        my ($y) = @_;
        $x + $y
    }
}

my $add5 = adder(5);
print &$add5(1) == 6 ? "ok\n" : "not ok\n";

JavaScript

var adder = function (x) {
    return function (y) {
        return x + y;
    };
};
add5 = adder(5);
add5(1) == 6

JavaScript (ES6)

const adder = x => y => x + y;
add5 = adder(5);
add5(1) == 6

Scheme

(define adder
    (lambda (x)
        (lambda (y)
           (+ x y))))
(define add5
    (adder 5))
(add5 1)
6

C# 3.5 or higher

Func<int, Func<int, int>> adder = 
    (int x) => (int y) => x + y; // `int` declarations optional
Func<int, int> add5 = adder(5);
var add6 = adder(6); // Using implicit typing
Debug.Assert(add5(1) == 6);
Debug.Assert(add6(-1) == 5);

// Closure example
int yEnclosed = 1;
Func<int, int> addWithClosure = 
    (x) => x + yEnclosed;
Debug.Assert(addWithClosure(2) == 3);

Swift

func adder(x: Int) -> (Int) -> Int{
   return { y in x + y }
}
let add5 = adder(5)
add5(1)
6

PHP

$a = 1;
$b = 2;

$lambda = function () use (&$a, &$b) {
    echo $a + $b;
};

echo $lambda();

Haskell

(\x y -> x + y) 

Java see this post

// The following is an example of Predicate : 
// a functional interface that takes an argument 
// and returns a boolean primitive type.

Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even.
boolean result = pred.test(4); // true

Lua

adder = function(x)
    return function(y)
        return x + y
    end
end
add5 = adder(5)
add5(1) == 6        -- true

Kotlin

val pred = { x: Int -> x % 2 == 0 }
val result = pred(4) // true

Ruby

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.

def adder(x)
  lambda { |y| x + y }
end
add5 = adder(5)
add5[1] == 6

Ruby being Ruby, there is a shorthand for lambdas, so you can define adder this way:

def adder(x)
  -> y { x + y }
end

OTHER TIPS

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);
}

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)

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:

  1. Declaring the function somewhere else (and having to look for it when you revisit the code later).
  2. Naming something that you're only using once.

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! ;-)

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

lambda

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.

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

@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.

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.

You can think of it as an anonymous function - here's some more info: Wikipedia - Anonymous Function

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.

Hello, Lambdas, version 1

template<typename F>

void Eval( const F& f ) {
        f();
}
void foo() {
        Eval( []{ printf("Hello, Lambdas\n"); } );
}

Hello, Lambdas, version 2:

void bar() {
    auto f = []{ printf("Hello, Lambdas\n"); };
    f();
}

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.)

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,

  1. lambda in an inline function which enable you to write a function in one straight line as does in mathematics
  2. lambda is anonymous

Hope, this helps.

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.

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]()()();

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).

I got it too. I`ve tried it in JS with this one:

var addAndMult = function(x) {
        return (function(y) {
            return (function(z) {
                return (x+y)*z; 
                });
            });
        };

It adds 2 to 4 then mults the result by 6. However I find it sometimes hard to read :(

Also I`ve made an interesting forEach function:

var forEach = function(arr) {
            return (function(x) {
            for (var i=0; arr[i]; i++) {
                 x(arr[i]);
             }
        });
    }

forEach([1,2,3,4,5])(console.log);

This method will iterate an array and performs an action - in the case printing to the console. Now I too get why labmdas are powerful.

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.

A Lambda Function, or a Small 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, or Block in C and Objective-C. Although lambda's meaning is quite similar for these languages it has slight distinctions sometimes.

Let's see how Lambda (Closure) works in Swift 4.2 with sorted() method – from normal function till the shortest expression:

let coffee: [String] = ["Cappuccino", "Espresso", "Latte", "Ristretto"]

1. Normal Function

func backward(_ n1: String, _ n2: String) -> Bool {
    return n1 > n2
}
var reverseOrder = coffee.sorted(by: backward)


// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]

2. Closure Expression

reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in
    return n1 > n2
})

3. Inline Closure Expression

reverseOrder = coffee.sorted(by: { (n1: String, n2: String) -> Bool in return n1 > n2 } )

4. Inferring Type From Context

reverseOrder = coffee.sorted(by: { n1, n2 in return n1 > n2 } )

5. Implicit Returns from Single-Expression Closures

reverseOrder = coffee.sorted(by: { n1, n2 in n1 > n2 } )

6. Shorthand Argument Names

reverseOrder = coffee.sorted(by: { $0 > $1 } )

// $0 and $1 are closure’s first and second String arguments.

7. Operator Methods

reverseOrder = coffee.sorted(by: >)

// RESULT: ["Ristretto", "Latte", "Espresso", "Cappuccino"]

Hope this helps.

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top