Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Learning C++ Functional Programming
Learning C++ Functional Programming
Learning C++ Functional Programming
Ebook475 pages3 hours

Learning C++ Functional Programming

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Apply Functional Programming techniques to C++ to build highly modular, testable, and reusable code

About This Book
  • Modularize your applications and make them highly reusable and testable
  • Get familiar with complex concepts such as metaprogramming, concurrency, and immutability
  • A highly practical guide to building functional code in C++ filled with lots of examples and real-world use cases
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.

What You Will Learn
  • Get to know the difference between imperative and functional approaches
  • See the use of first-class functions and pure functions in a functional style
  • Discover various techniques to apply immutable state to avoid side effects
  • Design a recursive algorithm effectively
  • Create faster programs using lazy evaluation
  • Structure code using design patterns to make the design process easier
  • Use concurrency techniques to develop responsive software
  • Learn how to use the C++ Standard Template Library and metaprogramming in a functional way to improve code optimization
In Detail

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.

Style and approach

This book uses a module-based approach, where each module will cover important aspects of functional programming in C++ and will help you develop efficient and robust applications through gaining a practical understanding.

LanguageEnglish
Release dateAug 10, 2017
ISBN9781787280588
Learning C++ Functional Programming

Read more from Anggoro Wisnu

Related to Learning C++ Functional Programming

Related ebooks

Programming For You

View More

Related articles

Reviews for Learning C++ Functional Programming

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Learning C++ Functional Programming - Anggoro Wisnu

    Learning C++ Functional Programming

    Learning C++ Functional Programming

    Metaprogramming, concurrency, lazy evaluation, and more

    Wisnu Anggoro

    BIRMINGHAM - MUMBAI

    < html PUBLIC -//W3C//DTD HTML 4.0 Transitional//EN http://www.w3.org/TR/REC-html40/loose.dtd>

    Learning C++ Functional Programming

    Copyright © 2017 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: August 2017

    Production reference: 1080817

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham

    B3 2PB, UK.

    ISBN 978-1-78728-197-4

    www.packtpub.com

    Credits

    About the Author

    Wisnu Anggoro is a Microsoft Certified Professional in C# programming and an experienced C/C++ developer. He has also authored the books Boost.Asio C++ Network Programming - Second Edition and Functional C# by Packt. He has been programming since he was in junior high school, which was about 20 years ago, and started developing computer applications using the BASIC programming language in the MS-DOS environment. He has solid experience in smart card programming, as well as desktop and web application programming, including designing, developing, and supporting the use of applications for SIM Card Operating System Porting, personalization, PC/SC communication, and other smart card applications that require the use of C# and C/C++. He is currently a senior smart card software engineer at CIPTA, an Indonesian company that specializes in innovation and technology for smart cards. He can be reached through his email at [email protected].

    First and foremost, I would like to thank God, the almighty, for providing me with this opportunity and granting me the capability to proceed successfully. To my wife and best motivator, Vivin, who never stopped supporting me in finishing what I started. To my beloved sons, Olav and Oliver, who are the source of my joy; you both never fail to make me happy every day. And to my parents and family for their inspiration.

    The best team at PACKT, especially Lawrence Veigas, my content development editor, for his effort to help me supply the best content for this book, and Denim Pinto, who invited me to author this book.

    Also, I would like to show my gratitude to Benediktus Dwi Desiyanto, my best mentor, teacher, and superior at CIPTA, who always supports me to leverage my skill set, for both hard and soft skills. And to all my friends at CIPTA, for the insight of C++ and functional programming I have learned from all of you.

    About the Reviewer

    Aivars Kalvans holds the position of Lead Software Architect at Tieto Latvia. He has been working on the Card Suite payment card system for more than 15 years and maintains many core C++ libraries and programs. He is also responsible for the C++ programming guidelines, secure coding training, and code reviews, and he organizes and speaks at internal C++ developer meetups as well.

    I would like to thank my lovely wife, Anete, and sons, KÄrlis, Gustavs, and Leo, for making life much more interesting.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787281973.

    If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

    Table of Contents

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Downloading the color images of this book

    Errata

    Piracy

    Questions

    Diving into Modern C++

    Getting closer with several new features in modern C++

    Defining the data type automatically using the auto keyword

    Querying the type of an expression using the decltype keyword

    Pointing to a null pointer

    Returning an iterator using non-member begin() and end() function

    Iterating over collections using range-based for loops

    Leveraging the use of C++ language with the C++ Standard Libraries

    Placing any objects in the container

    Using algorithms

    Simplifying the function notation using a Lambda expression

    Using the Lambda expression for a tiny function

    Using the Lambda expression for multiline functions

    Returning a value from the Lambda expression

    Capturing a value to the Lambda expression

    Preparing the value using initialization captures

    Writing a generic Lambda expression to be used many times with many different data types

    Avoiding manual memory management with smart pointers

    Replacing a raw pointer using unique_ptr

    Sharing objects using shared_ptr

    Tracking the objects using a weak_ptr pointer

    Storing many different data types using tuples

    Unpacking tuples values

    Returning a tuple value type

    Summary

    Manipulating Functions in Functional Programming

    Applying the first-class function in all functions

    Passing a function as another function's parameter

    Assigning a function to a variable

    Storing a function in the container

    Creating a new function from the existing functions at runtime

    Getting acquainted with three functional techniques in the higher-order function

    Executing each element list using map

    Extracting data using filter

    Combining all elements of a list using fold

    Avoiding the side effect with pure function

    Reducing a multiple arguments function with currying

    Summary

    Applying Immutable State to the Function

    Understanding the essential part from immutable object

    Modifying a local variable

    Modifying a variable passed into a function

    Preventing the modification of a value

    Applying the first-class function and the pure function to the immutable object

    Developing the immutable object

    Starting with a mutable object

    Refactoring a mutable object into an immutable one

    Enumerating the benefits of being immutable

    Summary

    Repeating Method Invocation Using Recursive Algorithm

    Repeating the function invocation recursively

    Performing the iteration procedure to repeat the process

    Performing the recursion procedure to repeat the process

    Recurring the immutable function

    Getting closer to tail recursion

    Getting acquainted with functional, procedural, and backtracking recursion

    Expecting results from functional recursion

    Running a task recursively in procedural recursion

    Backtracking recursion

    Summary

    Procrastinating the Execution Process Using Lazy Evaluation

    Evaluating the expression

    Running the expression immediately with strict evaluation

    Delaying the expression with non-strict evaluation

    The basic concept of lazy evaluation

    Delaying the process

    Caching the value using the memoization technique

    Optimizing the code using the memoization technique

    Lazy evaluation in action

    Designing Chunk and Row classes

    Concatenating several rows

    Iterating each Row class' element

    Generating the infinite integer row

    Generating an infinite prime numbers row

    Refactoring eager evaluation to lazy evaluation

    Summary

    Optimizing Code with Metaprogramming

    Introduction to metaprogramming

    Preprocessing the code using a macro

    Dissecting template metaprogramming in the Standard Library

    Building the template metaprogramming

    Adding a value to the variable in the template

    Mapping a function to the input parameters

    Choosing the correct process based on the condition

    Repeating the process recursively

    Selecting a type in compile-time

    Flow control with template metaprogramming

    Deciding the next process by the current condition

    Selecting the correct statement

    Looping the process

    Executing the code in compile-time

    Getting a compile-time constant

    Generating the class using a compile-time class generation

    Benefits and drawbacks of metaprogramming

    Summary

    Running Parallel Execution Using Concurrency

    Concurrency in C++

    Processing a single threading code

    Processing a multithreading code

    Synchronizing the threads using mutex

    Avoiding synchronization issues

    Unlocking the variable automatically

    Avoiding deadlock using recursive mutex

    Understanding the thread processing in a Windows operating system

    Working with handle

    Refactoring to a unique handle

    Triggering an event

    Calling an event from a thread

    Summary

    Creating and Debugging Application in Functional Approach

    Preparing an imperative class

    Refactoring the imperative class to become a functional class

    Passing a function as a parameter

    Adding a base class

    Transforming the class to become pure

    Filtering the condition and implementing a Lambda expression

    Implementing recursion and memoization techniques to the Customer class

    Debugging the code

    Starting the debugging tool

    Continuing and stepping the debugging process

    Setting and deleting the breakpoint

    Printing the object value

    Summary

    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.

    Warnings or important notes appear like this.

    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:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    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.

    Diving into Modern C++

    The C++ programming language has been changed dramatically since its invention in 1979. Some people in this era might be a little bit scared to code using C++ language since it is not user-friendly. The memory management we have to deal with sometimes makes people unwilling to use this language. Fortunately, since C++11--also known as modern C++, along with C++14 and C++17--has been released, numerous features have been introduced to simplify our code in the C++ language. Moreover, the best part of it is that the C++ programming language is a great language for any project, from low-level programming to web programming, as well as functional programming.

    This chapter is the best place to start our journey in this book, as it is addressed to the C++ programmers to refresh their knowledge and will discuss the following topics:

    Understanding several new features in modern C++

    Implementing the C++ Standard Libraries in modern C++

    The use of the Lambda expression and all features included in C++ Lambda

    Using smart pointer to avoid manual memory management

    Dealing with many return values using tuples

    Getting closer with several new features in modern C++

    So, what is new in modern C++ in comparison to the old one? There are so many changes in modern C++ compared to the old one, and the book pages will dramatically increase if we discuss all of them. However, we will discuss the new features in modern C++, which we should know about, to make us more productive in coding activities. We will discuss several new keywords, such as auto, decltype, and nullptr. We will also discuss the enhancement of the begin() and end() function that has now become a non-member class function. We will also discuss the augmented support for the for-each technique to iterate over collections using the range-based for loop techniques.

    The next few subsections in this chapter will also discuss the new features of modern C++, namely Lambda expressions, smart pointers, and tuples, which were just added in the C++11 release.

    Defining the data type automatically using the auto keyword

    Prior to the modern C++, the C++ language has a keyword named auto that is used to explicitly specify that the variable should have automatic duration. The automatic duration that adheres to the variable will create the variable at the point of definition (and initialized, if relevant) and destroy the variable when the block they are defined in is exited. For instance, the local variable will be created when it is defined at the beginning of the function and destroyed when the program exits the function

    Enjoying the preview?
    Page 1 of 1