Book Image

Learning C++ Functional Programming

By : Wisnu Anggoro
5 (1)
Book Image

Learning C++ Functional Programming

5 (1)
By: Wisnu Anggoro

Overview of this book

Functional programming allows developers to divide programs into smaller, reusable components that ease the creation, testing, and maintenance of software as a whole. Combined with the power of C++, you can develop robust and scalable applications that fulfill modern day software requirements. This book will help you discover all the C++ 17 features that can be applied to build software in a functional way. The book is divided into three modules—the first introduces the fundamentals of functional programming and how it is supported by modern C++. The second module explains how to efficiently implement C++ features such as pure functions and immutable states to build robust applications. The last module describes how to achieve concurrency and apply design patterns to enhance your application’s performance. Here, you will also learn to optimize code using metaprogramming in a functional way. By the end of the book, you will be familiar with the functional approach of programming and will be able to use these techniques on a daily basis.
Table of Contents (15 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Preface

Functional programming is a style of constructing the elements and structure of a computer program by composing pure functions, avoiding shared state, mutable data, and side-effects, like we usually see in mathematics. The variable in the code function represents the value of the function parameter, and it is similar to the mathematical function. The idea is that a programmer defines the functions that contain the expression, definition, and the parameters that can be expressed by a variable to solve problems. Functional programming is declarative rather than imperative, which means programming is done with expressions or declarations instead of statements. The application state of functional programming flows through pure functions, so it avoids the side effect. In contrast to imperative programming, the application state is usually shared and collocated with methods in objects. In imperative programming, the expressions are evaluated, and the resulting value is assigned to variables. For instance, when we group a series of expressions into a function, the resulting value depends upon the state of variables at that point in time. Because of the continuous changes in state, the order of evaluation matters. In functional programming, destructive assignment is forbidden, and each time an assignment happens, a new variable is induced. Best of all, functional code tends to be more concise and predictable, and easier to test than imperative or object-oriented code. Although there are some specifically designed languages for functional programming, such as Haskell and Scala, we can also use C++ to accomplish designing functional programming, as we will discuss throughout this book.

What this book covers

Chapter 1, Diving into Modern C++, provides an overview of modern C++, including the implementation of several new features in modern C++, such as the auto keyword, decltype keyword, null pointer, range-based for loop, standard template library, Lambda expressions, smart pointer, and tuple.

Chapter 2, Manipulating Functions in Functional Programming, covers the essential techniques in functional programming to manipulate a function; they are the first-class function technique, pure function, and currying technique. By applying the first-class function, we can treat our function as a data, which means it can be assigned to any variable instead of only being invoked as function. We also will apply the pure function technique so the function won't produce the side effect anymore. Moreover, to simplify the function, we can apply currying techniques, which will reduce the multiple arguments function by evaluating a sequence of functions with a single argument in each function.

Chapter 3, Applying Immutable State to the Function, explains how we implement the immutable object for the mutable object. We will also delve into first-class functions and pure functions, which we discussed in the previous chapter, to produce an immutable object.

Chapter 4, Repeating Method Invocation Using Recursive Algorithm, discusses the difference between iteration and recursion and why recursion techniques are better for functional programming. We will also enumerate the three kinds of recursion: functional, procedural, and backtracking recursion.

Chapter 5, Procrastinating the Execution Process Using Lazy Evaluation, explains how to delay the process of execution to get more efficient code. We will also implement caching and memoization techniques to make our code run faster.

Chapter 6, Optimizing Code with Metaprogramming, talks about running code with compile-time execution by using metaprogramming to optimize code. We will also discuss how to refactor flow control into template metaprogramming.

Chapter 7, Running Parallel Execution Using Concurrency, walks us through running multiple threads in C++ programming, as well as synchronizing threads to avoid deadlocks. We will also apply thread processing in a Windows operating system.

Chapter 8, Creating and Debugging Application in Functional Approach, elaborates all the techniques we discussed in the previous chapters to design a functional programming. Also, we will try to debug code to find a solution if there are unexpected results or the program crashes in the middle of execution.

What you need for this book

To walk through this book and successfully compile all the source code examples, you will require a personal computer that runs Microsoft Windows 8.1 (or later) and contains the following software:

  • The latest version of GCC, which supports C++11, C++14, and C++17 (during the writing of this book, the latest version was GCC v7.1.0)
  • The Microsoft C++ compiler provided in Microsoft Visual Studio 2017 for supporting C++11, C++14, and C++17 (for Chapter 7, Running Parallel Execution Using Concurrency)
  • Code::Blocks v16.01 (all sample code is written using the Code::Blocks IDE; however, it's optional to use this IDE)

Who this book is for

This book is for C++ developers comfortable with OOP who are interested in learning how to apply the functional paradigm to create robust and testable apps.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, and user input are shown as follows: "the auto keyword can also be applied to a function to deduce a function's return type automatically."

A block of code is set as follows:

    int add(int i, int j)
    {
      return i + j;
    }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

// Initializing a string variable
       Name n = {"Frankie Kaur"};
       cout << "Initial name = " << n.str;
       cout << endl;

New terms and important words are shown in bold.

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book--what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.
  2. Hover the mouse pointer on the SUPPORT tab at the top.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box.
  5. Select the book for which you're looking to download the code files.
  6. Choose from the drop-down menu where you purchased this book from.
  7. Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows
  • Zipeg / iZip / UnRarX for Mac
  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/LearningCPPFunctionalProgramming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningCPPFunctionalProgramming_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books--maybe a mistake in the text or the code--we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.