Story Melange
  • Home/Blog
  • Technical Blog
  • Book Reviews
  • Projects
  • Archive
  • About

On this page

  • What Are Lambda Expressions?
  • Immutability as goal
  • Syntax and Usage
    • How Do Lambda Expressions Work?
    • When Should You Use Them?

Clean coders use lambda expressions

python
c++
clean code
technical
In modern programming, lambda expressions have become an indispensable tool for concise and efficient code. They have their origin in functional programming but have made it to many programming languages. But how, when, and why should you use them? Let’s dive in.
Author

Dominik Lindner

Published

January 10, 2025

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.

Note

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 doubles x 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.
  • C++:

    • STL algorithms: std::sort, std::for_each, std::transform
    • Replacing verbose function objects
    • When relying heavily on functional programming.


© 2025 by Dr. Dominik Lindner
This website was created with Quarto


Impressum

Cookie Preferences