
PROGRAMMING LANGUAGES/C++ ee eBoo Functional Programming in C++ Fr k How to improve your C++ programs using functional techniques SEE FIRST PAGE ell-written code is easier to test and reuse, simpler to “Offers precise, easy-to- parallelize, and less error prone. Mastering the functional understand, and engaging Wstyle of programming can help you tackle the demands of explanations of functional Functional Programming in C modern apps and will lead to simpler expression of complex program concepts.” logic, graceful error handling, and elegant concurrency. C++ supports —Sumant Tambe, LinkedIn FP with templates, lambdas, and other core language features, along with many parts of the STL. “An excellent read. Comprehen- sive code examples illustrate the Functional Programming in C++ helps you unleash the implementation of functional functional side of your brain, as you gain a powerful new perspective programming patterns using on C++ coding. You’ll discover dozens of examples, diagrams, and C++14/C++17 constructs.” illustrations that break down the functional concepts you can apply in C++, including lazy evaluation, function objects and invokables, —Keerthi Shetty FactSet Research Systems algebraic data types, and more. As you read, you’ll match FP techniques with practical scenarios where they offer the most benefit. “Provides elegant, easy-to-grasp, ready-to-use examples that What’s inside will improve the way you think • Writing safer code with no performance penalties about coding.” • Explicitly handling errors through the type system —Nikos Athanasiou, BETA CAE Systems • Extending C++ with new control structures • Composing tasks with DSLs “Presents a new way of writing quality software and a new way Written for developers with two or more years of experience of thinking.” coding in C++. —Gian Lorenzo Meocci, CommProve is a core developer at KDE and has been coding in C++ Sample Chapter since 1998. He teaches modern C++ and functional programming at “Particularly valuable for the Faculty of Mathematics at the University of Belgrade. intermediate/advanced C++ ++ developers who want to embrace reactive-style programming.” To download their free eBook in PDF, ePub, and Kindle formats, owners of this book should visit manning.com/books/functional-programming-in-c-plus-plus —Marco Massenzio, Apple MANNING US $49.99 / Can $65.99 [including eBook] MANNING MANNING www.itbook.store/books/9781617293818 Functional Programming in C++ by Ivan Cukic Chapter 1 Copyright 2018 Manning Publications www.itbook.store/books/9781617293818 brief contents 1 ■ Introduction to functional programming 1 2 ■ Getting started with functional programming 21 3 ■ Function objects 45 4 ■ Creating new functions from the old ones 71 5 ■ Purity: Avoiding mutable state 100 6 ■ Lazy evaluation 122 7 ■ Ranges 142 8 ■ Functional data structures 158 9 ■ Algebraic data types and pattern matching 174 10 ■ Monads 199 11 ■ Template metaprogramming 226 12 ■ Functional design for concurrent systems 248 13 ■ Testing and debugging 274 v www.itbook.store/books/9781617293818 Introduction to functional programming This chapter covers 1 ¡ Understanding functional programming ¡ Thinking about intent instead of algorithm steps ¡ Understanding pure functions ¡ Benefits of functional programming ¡ C++’s evolution into a functional programming language As programmers, we’re required to learn more than a few programming languages during our lifetime, and we usually end up focusing on two or three that we’re most comfortable with. It’s common to hear somebody say that learning a new program- ming language is easy—that the differences between languages are mainly in the syntax, and that most languages provide roughly the same features. If we know C++, it should be easy to learn Java or C#, and vice versa. This claim does have some merit. But when learning a new language, we usually end up trying to simulate the style of programming we used in the previous lan- guage. When I first worked with a functional programming language at my univer- sity, I began by learning how to use its features to simulate for and while loops and if-then-else branching. That was the approach most of us took, just to be able to pass the exam and never look back. 1 www.itbook.store/books/9781617293818 2 CHAPTER 1 Introduction to functional programming There’s a saying that if the only tool you have is a hammer, you’ll be tempted to treat every problem like a nail. This also applies the other way around: if you have a nail, you’ll want to use whatever tool you’re given as a hammer. Many programmers who check out a functional programming language decide that it isn’t worth learning, because they don’t see the benefits; they try to use the new tool the same way they used the old one. This book isn’t meant to teach you a new programming language, but it is meant to teach you an alternative way of using a language (C++): a way that’s different enough that it’ll often feel like you’re using a new language. With this new style of programming, you can write more-concise programs and write code that’s safer, easier to read and rea- son about, and, dare I say, more beautiful than the code usually written in C++. 1.1 What is functional programming? Functional programming is an old programming paradigm that was born in academia during the 1950s; it stayed tied to that environment for a long time. Although it was always a hot topic for scientific researchers, it was never popular in the “real world.” Instead, imperative languages (first procedural, later object-oriented) became ubiquitous. It has often been predicted that one day functional programming languages will rule the world, but it hasn’t happened yet. Famous functional languages such as Haskell and Lisp still aren’t on the top-10 lists of the most popular programming languages. Those lists are reserved for traditionally imperative languages including C, Java, and C++. Like most predictions, this one needs to be open to interpretation to be considered fulfilled. Instead of functional programming languages becoming the most popular, something else is happening: the most popular programming languages have started introducing features inspired by functional programming languages. What is functional programming (FP)? This question is difficult to answer because no widely accepted definition exists. There’s a saying that if you ask two functional program- mers what FP is, you’ll get (at least) three different answers. People tend to define FP through related concepts including pure functions, lazy evaluation, pattern matching, and such. And usually, they list the features of their favorite language. In order not to alienate anyone, we’ll start with an overly mathematical definition from the functional programming Usenet group: Functional programming is a style of programming that emphasizes the evaluation of expressions, rather than execution of commands. The expressions in these languages are formed by using functions to combine basic values. A functional language is a language that supports and encourages programming in a functional style. —FAQ for comp.lang.functional Over the course of this book, we’ll cover various concepts related to FP. I’ll leave it up to you to pick your favorites that you consider essential for a language to be called functional. Broadly speaking, FP is a style of programming in which the main program building blocks are functions as opposed to objects and procedures. A program written in the functional style doesn’t specify the commands that should be performed to achieve the result, but rather defines what the result is. www.itbook.store/books/9781617293818 What is functional programming? 3 Consider a small example: calculating the sum of a list of numbers. In the imperative world, you implement this by iterating over the list and adding the numbers to the accu- mulator variable. You explain the step-by-step process of how to sum a list of numbers. On the other hand, in the functional style, you need to define only what a sum of a list of numbers is. The computer knows what to do when it’s required to calculate a sum. One way you can do this is to say that the sum of a list of numbers equals the first element of the list added to the sum of the rest of the list, and that the sum is zero if the list is empty. You define what the sum is without explaining how to calculate it. This difference is the origin of the terms imperative and declarative programming. Imperative means you command the computer to do something by explicitly stating each step it needs to perform in order to calculate the result. Declarative means you state what should be done, and the programming language has the task of figuring out how to do it. You define what a sum of a list of numbers is, and the language uses that definition to calculate the sum of a given list of numbers. 1.1.1 Relationship with object-oriented programming It isn’t possible to say which is better: the most popular imperative paradigm, object-oriented programming (OOP); or the most commonly used declarative one, the FP paradigm. Both have advantages and weaknesses. The object-oriented paradigm is based on creating abstractions for data. It allows the programmer to hide the inner representation inside an object and provide only a view of it to the rest of the world via the object’s API. The FP style creates abstractions on the functions. This lets you create more-complex control structures than the underlying language provides. When C++11 introduced the range-based for loop (sometimes called foreach), it had to be implemented in every C++ compiler (and there are many of them).
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages24 Page
-
File Size-