logo

Programming Languages - Lambda

Last Updated: 2024-01-21

C++

#include <algorithm>
#include <cmath>

std::sort(x, x + n,
    [](float a, float b) {
        return (std::abs(a) < std::abs(b));
    }
);

In C++ you have to specify the values that are captured by the lambda. In other languages (e.g. Java and Rust) the compiler handles capturing without specifying the values.

  • []: capture clause
  • (): parameter list

Java

Collections.sort(vals, (a, b) ->
    Integer.compare(Math.pow(a, p), Math.pow(b, p)));

JavaScript

(a) => a * 2;

Python

Syntax: lambda arguments: expression.

E.g. lambda a: a + 1

  • no multiple statements in a lambda.
  • lambda cannot contain assignment.
>>> sorted([3, -2, -4, 5, 1], key=lambda x: abs(x))
[1, -2, 3, -4, 5]

Ruby

proc

>> multiply = -> x, y { x * y }
=> #<Proc (lambda)>
>> multiply.call(6, 9)
=> 54
>> multiply.call(2, 3)
=> 6
>> multiply[3, 4]
=> 12