Lambdas & Closures
Lambdas and closures.
C++
Rust
Java
vector<int> vals = {-1, -2, -3, 1, 2, 3, 0};
int p = 2;
sort(vals.begin(),
vals.end(),
[p](int a, int b) {
return pow(a, p) < pow(b, p);
});
let mut vals = [-1, -2, -3, 1, 2, 3, 0];
let p = 2;
vals.sort_by(|a :&isize, b :&isize|
a.pow(p).cmp(&b.pow(p)));
List<Integer> vals = Arrays.asList(-1, -2, -3, 0, 1, 2, 3);
int p = 2;
Collections.sort(vals, (a, b) ->
Integer.compare(Math.pow(a, p), Math.pow(b, p)));
Lambdas (and closures) were added to C++ in C++11 and to Java in Java 8. Rust has always had them.
In C++ you are required to specify the values that are captured by the lambda. In Java and Rust the compiler handles capturing without specifying the values.