Functional Programming in C++
eBook - ePub

Functional Programming in C++

Ivan Cukic

Condividi libro
  1. 320 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Functional Programming in C++

Ivan Cukic

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Summary Functional Programming in C++ teaches developers the practical side of functional programming and the tools that C++ provides to develop software in the functional style. This in-depth guide is full of useful diagrams that help you understand FP concepts and begin to think functionally.Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology Well-written code is easier to test and reuse, simpler to parallelize, and less error prone. Mastering the functional style of programming can help you tackle the demands of modern apps and will lead to simpler expression of complex program logic, graceful error handling, and elegant concurrency. C++ supports FP with templates, lambdas, and other core language features, along with many parts of the STL. About the Book Functional Programming in C++ helps you unleash the functional side of your brain, as you gain a powerful new perspective on C++ coding. You'll discover dozens of examples, diagrams, and illustrations that break down the functional concepts you can apply in C++, including lazy evaluation, function objects and invokables, algebraic data types, and more. As you read, you'll match FP techniques with practical scenarios where they offer the most benefit. What's inside

  • Writing safer code with no performance penalties
  • Explicitly handling errors through the type system
  • Extending C++ with new control structures
  • Composing tasks with DSLs


About the Reader Written for developers with two or more years of experience coding in C++. About the Author Ivan ?uki? is a core developer at KDE and has been coding in C++ since 1998. He teaches modern C++ and functional programming at the Faculty of Mathematics at the University of Belgrade. Table of Contents

  • Introduction to functional programming
  • Getting started with functional programming
  • Function objects
  • Creating new functions from the old ones
  • Purity: Avoiding mutable state
  • Lazy evaluation
  • Ranges
  • Functional data structures
  • Algebraic data types and pattern matching
  • Monads
  • Template metaprogramming
  • Functional design for concurrent systems
  • Testing and debugging

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Functional Programming in C++ è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Functional Programming in C++ di Ivan Cukic in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in C++. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Editore
Manning
Anno
2018
ISBN
9781638355663

1
Introduction to functional programming

This chapter covers
  • 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 programming 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 language. When I first worked with a functional programming language at my university, 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.
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 reason 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 programmers 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.
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 accumulator 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). Using FP techniques, it was possible to do this without changing the compiler. Many third-party libraries implemented their own versions of the range-based for loop over the years. When we use FP idiom...

Indice dei contenuti