Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Hands-On Functional Programming with C++
Hands-On Functional Programming with C++

Hands-On Functional Programming with C++: An effective guide to writing accelerated functional code using C++17 and C++20

Arrow left icon
Profile Icon Alexandru Bolboaca
Arrow right icon
AU$24.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (2 Ratings)
Paperback Jun 2019 358 pages 1st Edition
eBook
AU$37.99 AU$42.99
Paperback
AU$53.99
Subscription
Free Trial
Renews at AU$24.99p/m
Arrow left icon
Profile Icon Alexandru Bolboaca
Arrow right icon
AU$24.99 per month
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (2 Ratings)
Paperback Jun 2019 358 pages 1st Edition
eBook
AU$37.99 AU$42.99
Paperback
AU$53.99
Subscription
Free Trial
Renews at AU$24.99p/m
eBook
AU$37.99 AU$42.99
Paperback
AU$53.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Hands-On Functional Programming with C++

An Introduction to Functional Programming

Why is functional programming useful? Functional programming constructs have popped up in all major programming languages in the past decade. Programmers have enjoyed their benefits—simplified loops, more expressive code, and simple parallelization. But there's more to it—decoupling from time, enabling opportunities to remove duplication, composability, and a simpler design. Higher adoption of functional programming (including the large-scale adoption of Scala in the financial sector) means more opportunities for you once you know and understand it. While we will take a deep dive into functional programming in this book to help you learn, remember that functional programming is another tool to add to your toolbox—one that you can choose to use when the problem and the context fits.

The following topics will be...

Technical requirements

An introduction to functional programming

My first experience with functional programming was at university. I was a 20-year-old geek who was interested in Sci-Fi, reading, and programming; programming was the highlight of my academic life. Everything to do with C++, Java, MATLAB, and a few other programming languages that we used was fun for me. Unfortunately, I can't say the same thing about the disciplines around electrical engineering, circuits, or compiler theory. I just wanted to write code!

Based on my interests, functional programming should have been a very fun course for me. Our teacher was very passionate. We had to write code. But something went wrong—I didn't click with what the teacher was telling us. Why were lists so interesting? Why was the syntax so backward and full of parentheses? Why would I use these things when it was much simpler to write...

Functional programming constructs are everywhere

Around 10 years after I finished the university functional programming course, I had a casual chat with my friend, Felix. As any two geeks, we would rarely see each other, but we had, for years, an ongoing conversation on instant messaging discussing all kinds of nerdy topics and, of course, programming.

Somehow, the topic of functional programming came up. Felix pointed out that one of my favorite and most enjoyable programming languages, LOGO, was, in fact, a functional programming language.

LOGO is an educational programming language whose main characteristic is utilization of so-called turtle graphics.

It was obvious in retrospect; here is how to write a function that draws a square in the KTurtle version of LOGO:

learn square {
repeat 4 {forward 50 turnright 90}
}

The result is shown in the following screenshot:

Can you...

Structured loops versus functional loops

It's hardly a surprise that one of the first things that we learn as programmers is how to write a loop. One of my first loops in C++ was printing the numbers from 1 to 10:

for(int i = 0; i< 10; ++i){
cout << i << endl;
}

As a curious programmer, I took this syntax for granted, went over its peculiarities and complications, and just used it. Looking back, I realize that there are a few unusual things about this construct. First, why start with 0? I've been told it's a convention, due to historical reasons. Then, the for loop has three statements—an initialization, a condition, and an increment. This sounds slightly too complicated for what we're trying to achieve. Finally, the end condition forced me into more off-by-one errors than I'd like to admit.

At this point, you will realize that...

Immutability

We've already understood that a certain level of immutability is preferred in C++; the common example is as follows:

class ...{
int add(const int& first, const int& second) const{
return first + second;
}
}

The const keyword clearly communicates a few important constraints on the code, such as the following:

  • The function does not change any of its arguments before returning.
  • The function does not change any data member of the class it belongs to.

Let's now imagine an alternate version of add, as follows

int uglyAdd(int& first, int& second){
first = first + second;
aMember = 40;
return first;
}

I called this uglyAdd for a reason—I don't tolerate code like this when I'm programming! This function violates the principle of minimal surprise and does too many things. Reading the function code reveals nothing...

OOP versus functional design styles

An important part of my job is to work with programmers and help them to improve the way they write code. To do so, I try my best to come up with simple explanations for complex ideas. I have one such explanation for software design. Software design is, for me, the way we structure the code such that we optimize it for business purposes.

I like this definition because it's plain and short. But one thing bugged me after I started experimenting with functional constructs; that is, functional programming leads to code such as the following:

const Sums sumsWithFunctionalLoopsSimplified(const vector<int>& numbers){
Sums theTotals(
sum(filter(numbers, isEven)),
sum(filter(numbers, isOdd)),
sum(numbers)
);
return theTotals;
}

Writing similar code in OOP style would most likely mean creating classes and using...

Composability and removing duplication

We have already seen an example of where we had a fair amount of duplication:

const Sums sumsWithFunctionalLoops(const vector<int>& numbers){
Sums theTotals;
vector<int> evenNumbers;
copy_if(numbers.begin(), numbers.end(), back_inserter(evenNumbers),
isEven);
theTotals.evenSum = accumulate(evenNumbers.begin(),
evenNumbers.end(), 0);

vector<int> oddNumbers;
copy_if(numbers.begin(), numbers.end(), back_inserter(oddNumbers),
isOdd);
theTotals.oddSum= accumulate(oddNumbers.begin(), oddNumbers.end(),
0);

theTotals.total = accumulate(numbers.begin(), numbers.end(), 0);

return theTotals;
}

We managed to reduce it using functions, as shown in the following code:

template<class UnaryPredicate>
const vector<int> filter(const vector<int>& input, UnaryPredicate filterFunction...

Technical requirements

What is a pure function?

Let's take a moment to think about a simple everyday experience. When you turn the light switch, one of two things happen:

  • If the light is on, it turns off
  • If the light is off, it turns on

The behavior of a light switch is highly predictable. It's so predictable that, when the light doesn't turn on, you immediately think that something is wrong—that is, with the light bulb, the fuses, or the switch itself.

Here are some of the things that you don't expect to happen when you turn the switch on or off:

  • Your fridge doesn't go off
  • Your neighbor's lights don't turn on
  • Your bathroom sink water doesn't turn on
  • Your mobile phone doesn't reset

Why would all these things happen when you turn the light switch on? That would be highly chaotic; we wouldn't want chaos in our lives, right?

Yet, programmers often...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Learn programming concepts such as loops, expressive code, and simple parallelization
  • Understand the working of lambdas and currying and write Pure functions
  • Explore event sourcing and other functional patterns to improve the efficiency of your applications

Description

Functional programming enables you to divide your software into smaller, reusable components that are easy to write, debug, and maintain. Combined with the power of C++, you can develop scalable and functional applications for modern software requirements. This book will help you discover the functional features in C++ 17 and C++ 20 to build enterprise-level applications. Starting with the fundamental building blocks of functional programming and how to use them in C++, you’ll explore functions, currying, and lambdas. As you advance, you’ll learn how to improve cohesion and delve into test-driven development, which will enable you in designing better software. In addition to this, the book covers architectural patterns such as event sourcing to help you get to grips with the importance of immutability for data storage. You’ll even understand how to “think in functions” and implement design patterns in a functional way. By the end of this book, you’ll be able to write faster and cleaner production code in C++ with the help of functional programming.

Who is this book for?

This book is for C++ developers who want to learn functional programming but have little to no knowledge of the paradigm. Although no prior knowledge of functional programming is necessary, basic C++ programming experience will help you understand key concepts covered in the book.

What you will learn

  • Understand the fundamentals of functional programming
  • Structure your code by understanding the building blocks of functional programming
  • Compare design styles in functional programming and object-oriented programming (OOP)
  • Use the concept of currying to create new functions in C++
  • Become skilled at implementing design patterns in a functional way
  • Get to grips with multithreading by means of functional programming
  • Learn how to improve memory consumption when using functional constructs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 28, 2019
Length: 358 pages
Edition : 1st
Language : English
ISBN-13 : 9781789807332
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 28, 2019
Length: 358 pages
Edition : 1st
Language : English
ISBN-13 : 9781789807332
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
AU$249.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts
AU$349.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 190.97
Hands-On Functional Programming with C++
AU$53.99
Hands-On Design Patterns with C++
AU$75.99
C++ Data Structures and Algorithm Design Principles
AU$60.99
Total AU$ 190.97 Stars icon

Table of Contents

22 Chapters
Section 1: Functional Building Blocks in C++ Chevron down icon Chevron up icon
An Introduction to Functional Programming Chevron down icon Chevron up icon
Understanding Pure Functions Chevron down icon Chevron up icon
Deep Dive into Lambdas Chevron down icon Chevron up icon
The Idea of Functional Composition Chevron down icon Chevron up icon
Partial Application and Currying Chevron down icon Chevron up icon
Section 2: Design with Functions Chevron down icon Chevron up icon
Thinking in Functions - from Data in to Data out Chevron down icon Chevron up icon
Removing Duplication with Functional Operations Chevron down icon Chevron up icon
Improving Cohesion Using Classes Chevron down icon Chevron up icon
Test-Driven Development for Functional Programming Chevron down icon Chevron up icon
Section 3: Reaping the Benefits of Functional Programming Chevron down icon Chevron up icon
Performance Optimization Chevron down icon Chevron up icon
Property-Based Testing Chevron down icon Chevron up icon
Refactoring to and through Pure Functions Chevron down icon Chevron up icon
Immutability and Architecture - Event Sourcing Chevron down icon Chevron up icon
Section 4: The Present and Future of Functional Programming in C++ Chevron down icon Chevron up icon
Lazy Evaluation Using the Ranges Library Chevron down icon Chevron up icon
STL Support and Proposals Chevron down icon Chevron up icon
Standard Language Support and Proposals Chevron down icon Chevron up icon
Assessments Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 50%
4 star 0%
3 star 50%
2 star 0%
1 star 0%
Mehnen Jun 15, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
made the learning of functional programming easy ... geed examples !
Amazon Verified review Amazon
Kostas Nov 26, 2019
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
Note reg. my review : I am not a C++ developer.Been a scala developer picking a C++ hobby, this book was pleasant read overall, but probably the examples overused lambda's. The author notes that having a lot of standalone lambdas makes the code loose cohesion and I agree on that which is what made me not follow the code in the cards example due to too many standalone lambdas. (btw, a function declaration like int add(int a,int b) is also functional programming, the examples would be a lot easier to follow if they contained immutable domain model + functions)I would also expect to see how to create immutable classes and collections and things like higher order functions.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.

Modal Close icon
Modal Close icon