Cheatsheet: Data Structures
    Array / List
    Map / Dict
    Set
    Tuple
    Struct / Data Class
    Stacks
    Other Data Structures
    Collection Conversions
Cheatsheet: Control Flow
Cheatsheet: Class

Polyglot CheatSheet - Lambda

Updated: 2022-04-04

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