Clean coders use lambda expressions
What Are Lambda Expressions?
Lambda expressions are small, anonymous functions designed for short-lived tasks with limited scope. Unlike named functions, they do not require a definition at module level. Instead they exist within a function. This makes them ideal for any operation where defining a full-fledged function would be overkill.
Immutability as goal
Lambda expressions originated from lambda calculus, a mathematical framework for describing functions. Functional programming languages like Lisp first adopted the concept, and it eventually trickled down to more general-purpose languages.
But why were lambdas introduced into Python and C++? The goal was to enable functional programming paradigms, like mapping, filtering, and reducing data.
The benefit of functional programming is that it renders a function immutable.
This has enormous benefits for complex logic and especially for multithreaded applications. By making a function immutable, race conditions and deadlocks can not origin from this function. By limiting the mutuabitliy of code to certain blocks, multithreading errors are easier to find.
Syntax and Usage
How Do Lambda Expressions Work?
The syntax differs between Python and C++:
Python:
lambda arguments: expression
Example:lambda x: x * 2
creates a function that doubles the input.C++:
[capture](arguments) { body }
Example:[&](int x) { return x * 2; }
defines a lambda that doublesx
while capturing variables by reference.
When Should You Use Them?
Python:
- Sorting:
sorted(data, key=lambda x: x.value)
- Filtering:
filter(lambda x: x > 10, numbers)
- Functional constructs:
map
,reduce
- One-liners: Embedding logic where defining a named function is unnecessary.
- Sorting:
C++:
- STL algorithms:
std::sort
,std::for_each
,std::transform
- Replacing verbose function objects
- When relying heavily on functional programming.
- STL algorithms: