Overview

1 Introduction to functional programming

This opening chapter introduces the functional programming mindset in the context of modern C++, contrasting imperative “how to do it” code with declarative “what to achieve” expressions. It frames functions as primary building blocks and emphasizes expressing intent through composition and higher-level abstractions rather than managing stepwise control flow and state. Through simple examples (like counting lines across files), it shows the progression from manual loops to standard algorithms and finally to range-based pipelines, illustrating how functional idioms make code shorter, clearer, and closer to the problem statement while coexisting productively with object-oriented design in a multiparadigm language.

A central theme is purity: preferring functions without observable side effects and minimizing mutable state to reduce bugs and make reasoning easier. The chapter explains a pragmatic view of pure functions—those that appear side-effect-free to their callers—even when implementation details perform unavoidable mutations (e.g., I/O). Thinking functionally means decomposing problems into small, composable transformations and lifting single-item functions to operate over collections, much like stations on an assembly line. The benefits include brevity and readability, safer refactoring, easier parallelization (thanks to the absence of shared mutable state), and fewer opportunities for subtle defects.

The text also surveys C++’s evolution toward functional styles: templates enabling generic algorithms, passing function-like entities, and later features (such as auto and lambdas) that make higher-order programming practical and expressive. It advocates leaning on well-crafted library abstractions (STL algorithms and ranges) for both clarity and “continuous optimization” as compilers and libraries improve. Finally, it outlines what readers will learn: higher-order functions, immutable design strategies, ranges for composable dataflow, algebraic data types to constrain program states, and monadic patterns for building complex yet modular systems—skills that yield concise, maintainable, and scalable C++ code.

The program input is a list of files. The program needs to return the number of newlines in each file as its output.
c01_01.png
If you allow the user to modify the text while you’re saving it, incomplete or invalid data could be saved, thus creating a corrupted file.
c01_02.png
If you either create a full copy or use a structure that can remember multiple versions of data at the same time, you can decouple the processes of saving the file and changing the text in the text editor.
c01_03.png
This example needs to modify a couple of independent variables while counting the number of newlines in a single file. Some changes depend on each other, and others don’t.
c01_04.png
When thinking functionally, you consider the transformations you need to apply to the given input to get the desired output as the result.
c01_05.png
You can perform the same transformation on each element in a collection. This allows you to look at the simpler problem of transforming a single item instead of a collection of items.
c01_06.png
You can decompose a bigger problem of counting the number of lines in a file whose name you have into two smaller problems: opening a file, given its name; and counting the number of lines in a given file.
c01_07.png
By using transform, you can create functions that can process collections of items from functions that can process only one item at a time.
c01_08.png
Function composition and lifting can be compared to a moving assembly line. Different transformations work on single items. By lifting these transformations to work on collections of items and composing them so that the result of one transformation is passed on to the next transformation, you get an assembly line that applies a series of transformations to as many items as you want.
c01_09.png

Summary

  • The main philosophy of functional programming is that you shouldn’t concern yourself with the way something should work, but rather with what it should do.
  • Both approaches—functional programming and object-oriented programming—have a lot to offer. You should know when to use one, when to use the other, and when to combine them.
  • C++ is a multiparadigm programming language you can use to write programs in various styles—procedural, object-oriented, and functional—and combine those styles with generic programming.
  • Functional programming goes hand-in-hand with generic programming, especially in C++. They both inspire programmers not to think at the hardware level, but to move higher.
  • Function lifting lets you create functions that operate on collections of values from functions that operate only on single values. With function composition, you can pass a value through a chain of transformations, and each transformation passes its result to the next.
  • Avoiding mutable state improves the correctness of code and removes the need for mutexes in multithreaded code.
  • Thinking functionally means thinking about the input data and the transformations you need to perform to get the desired output.

FAQ

What is functional programming (FP)?FP is a programming style that emphasizes evaluating expressions and composing functions to describe what a result is, rather than issuing step-by-step commands. Programs are built by combining functions over values, and languages (or styles) that support and encourage this make it natural to write declarative code.
How does declarative FP differ from imperative programming?Imperative code specifies how to do something via ordered steps and mutable state; declarative FP states what the result should be and relies on reusable abstractions to do the work. For example, instead of writing loops to sum or count, you express the intent (sum, count, transform) and let library algorithms perform the details.
How can the “count lines in files” task be expressed functionally in C++?Replace manual loops and counters with standard algorithms: use a function that counts newlines in a stream (e.g., with std::count over stream iterators), then map that function over the list of filenames using std::transform. With ranges, this becomes an even clearer pipeline: files passed through transform(open_file) and then transform(count_lines), returning the results with minimal boilerplate.
How does FP relate to object-oriented programming (OOP) in C++?They are complementary. OOP abstracts data behind types and interfaces, while FP abstracts computation by composing functions and creating higher-level control structures. Modern C++ is multiparadigm: the STL and algorithms show how FP ideas (with templates and callables) can coexist and enhance typical OOP code.
What are pure functions, and what’s a practical definition in C++?Pure functions always return the same result for the same inputs and have no observable side effects. Strict purity forbids state changes and I/O, which is impractical, so a useful working definition is “no externally observable side effects”: isolate stateful/I/O parts at the edges and keep most functions pure from the caller’s perspective.
Why avoid mutable state?Mutable state couples parts of a program and is a frequent source of bugs, especially under concurrency. The text-editor save example shows how shared, changing data can produce corrupted results; using immutable data or isolated copies decouples operations and reduces interference, making code easier to reason about and refactor.
What are function composition and lifting, and how do they help?Composition chains functions so the output of one becomes the input of the next (for example, open a file, then count its lines). Lifting generalizes a function from single values to structures of values (e.g., collections); std::transform effectively lifts a per-item function so it can process an entire container, enabling clear “assembly line” pipelines.
What practical benefits of FP does the chapter highlight?- Brevity and readability: less boilerplate and clearer intent using algorithms and pipelines. - Easier concurrency: pure functions avoid shared mutable state, reducing synchronization needs. - Continuous optimization: by relying on standard abstractions, your code benefits automatically from compiler and library improvements.
Which C++ features enable functional-style programming?Templates and the STL algorithms (generic programming) allow passing callables to parameterize behavior. Modern C++ adds lambdas and auto for concise callables and type inference, and newer facilities like ranges, concepts, and coroutines (introduced via the standard’s evolution) further streamline functional composition.
How should I start thinking functionally in C++?Identify inputs and desired outputs, then design a sequence of small, composable transformations to map one to the other. Prefer pure functions, minimize local mutation, and use standard algorithms or ranges to express intent (transform, filter, fold) instead of writing explicit loops.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C++ ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C++ ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Functional Programming in C++ ebook for free