Functional Programming in C++
eBook - ePub

Functional Programming in C++

Ivan Cukic

Compartir libro
  1. 320 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Functional Programming in C++

Ivan Cukic

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Functional Programming in C++ un PDF/ePUB en línea?
Sí, puedes acceder a Functional Programming in C++ de Ivan Cukic en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C++. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Editorial
Manning
Año
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...

Índice