Programming Languages - Lambda
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]