Functional Programming In
Total Page:16
File Type:pdf, Size:1020Kb
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++ 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 Functional Programming in C++ Functional Programming in C++ IVAN CˇUKIC´ MANNING SHELTER ISLAND For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2019 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. ∞ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid- free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Marina Michaels 20 Baldwin Road Technical development editor: Mark Elston PO Box 761 Review editor: Aleksandar Dragosavljevic´ Shelter Island, NY 11964 Project editor: Lori Weidert Copy editor: Sharon Wilkey Proofreader: Tiffany Taylor Technical proofreader: Yongwei Wu Typesetter: Happenstance Type-O-Rama Cover designer: Leslie Haimes ISBN 9781617293818 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – SP – 23 22 21 20 19 18 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 contents preface xiii acknowledgments xv about this book xvii about the author xxi Introduction to functional programming 1 1.1 What is functional programming? 2 1 Relationship with object-oriented programming 3 ■ A concrete example of imperative vs. declarative programming 3 1.2 Pure functions 8 1.2.1 Avoiding mutable state 10 1.3 Thinking functionally 12 1.4 Benefits of functional programming 14 Code brevity and readability 15 ■ Concurrency and synchronization 16 ■ Continuous optimization 17 1.5 Evolution of C++ as a functional programming language 17 1.6 What you’ll learn in this book 19 vii viiiviii CONTENTS Getting started with functional programming 21 2.1 Functions taking functions? 22 2 2.2 Examples from the STL 24 Calculating averages 24 ■ Folding 27 ■ String trimming 31 ■ Partitioning collections based on a predicate 32 ■ Filtering and transforming 34 2.3 Composability problems of STL algorithms 36 2.4 Writing your own higher-order functions 38 Receiving functions as arguments 38 ■ Implementing with loops 38 ■ Recursion and tail-call optimization 40 ■ Implementing using folds 43 Function objects 45 3.1 Functions and function objects 46 3 Automatic return type deduction 46 ■ Function pointers 49 ■ Call operator overloading 50 ■ Creating generic function objects 52 3.2 Lambdas and closures 54 Lambda syntax 55 ■ Under the hood of lambdas 56 ■ Creating arbitrary member variables in lambdas 59 ■ Generic lambdas 60 3.3 Writing function objects that are even terser than lambdas 61 Operator function objects in STL 64 ■ Operator function objects in other libraries 65 3.4 Wrapping function objects with std::function 68 Creating new functions from the old ones 71 4.1 Partial function application 72 4 A generic way to convert binary functions into unary ones 74 ■ Using std::bind to bind values to specific function arguments 77 ■ Reversing the arguments of a binary function 79 ■ Using std::bind on functions with more arguments 80 ■ Using lambdas as an alternative for std::bind 83 4.2 Currying: a different way to look at functions 85 Creating curried functions the easier way 87 ■ Using currying with database access 88 ■ Currying and partial function application 90 CONTENTS ix 4.3 Function composition 92 4.4 Function lifting, revisited 95 Reversing a list of pairs 97 Purity: Avoiding mutable state 100 5.1 Problems with the mutable state 101 5 5.2 Pure functions and referential transparency 103 5.3 Programming without side effects 106 5.4 Mutable and immutable state in a concurrent environment 110 5.5 The importance of being const 113 Logical and internal const-ness 115 ■ Optimizing member functions for temporaries 117 ■ Pitfalls with const 119 Lazy evaluation 122 6.1 Laziness in C++ 123 6 6.2 Laziness as an optimization technique 126 Sorting collections lazily 126 ■ Item views in the user interfaces 128 ■ Pruning recursion trees by caching function results 129 ■ Dynamic programming as a form of laziness 131 6.3 Generalized memoization 133 6.4 Expression templates and lazy string concatenation 136 Purity and expression templates 140 Ranges 142 7.1 Introducing ranges 144 7 7.2 Creating read-only views over data 145 Filter function for ranges 145 ■ Transform function for ranges 146 ■ Lazy evaluation of range values 147 7.3 Mutating values through ranges 149 7.4 Using delimited and infinite ranges 151 Using delimited ranges to optimize handling input ranges 151 ■ Creating infinite ranges with sentinels 152 7.5 Using ranges to calculate word frequencies 154 xx CONTENTS Functional data structures 158 8.1 Immutable linked lists 159 8 Adding elements to and removing them from the start of a list 159 ■ Adding elements to and removing them from the end of a list 161 ■ Adding elements to and removing them from the middle of a list 162 ■ Memory management 163 8.2 Immutable vector-like data structures 165 Element lookup in bitmapped vector tries 167 ■ Appending elements to bitmapped vector tries 168 ■ Updating elements in bitmapped vector tries 171 ■ Removing elements from the end of the bitmapped vector trie 171 ■ Other operations and the overall efficiency of bitmapped vector tries 171 Algebraic data types and pattern matching 174 9.1 Algebraic data types 175 9 Sum types through inheritance 176 ■ Sum types through unions and std::variant 179 ■ Implementing specific states 182 ■ Special sum type: Optional values 184 ■ Sum types for error handling 186 9.2 Domain modeling with algebraic data types 191 The naive approach, and where it falls short 192 ■ A more sophisticated approach: Top-down design 192 9.3 Better handling of algebraic data types with pattern matching 194 9.4 Powerful pattern matching with the Mach7 library 196 Monads 199 10.1 Not your father’s functors 200 10 Handling optional values 201 10.2 Monads: More power to the functors 204 10.3 Basic examples 207 10.4 Range and monad comprehensions