Functional Programming in C#
eBook - ePub

Functional Programming in C#

How to write better C# code

Enrico Buonanno

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

Functional Programming in C#

How to write better C# code

Enrico Buonanno

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Summary Functional Programming in C# teaches you to apply functional thinking to real-world problems using the C# language. The book, with its many practical examples, is written for proficient C# programmers with no prior FP experience. It will give you an awesome new perspective.Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology Functional programming changes the way you think about code. For C# developers, FP techniques can greatly improve state management, concurrency, event handling, and long-term code maintenance. And C# offers the flexibility that allows you to benefit fully from the application of functional techniques. This book gives you the awesome power of a new perspective. About the Book Functional Programming in C# teaches you to apply functional thinking to real-world problems using the C# language. You'll start by learning the principles of functional programming and the language features that allow you to program functionally. As you explore the many practical examples, you'll learn the power of function composition, data flow programming, immutable data structures, and monadic composition with LINQ. What's Inside

  • Write readable, team-friendly code
  • Master async and data streams
  • Radically improve error handling
  • Event sourcing and other FP patterns


About the Reader Written for proficient C# programmers with no prior FP experience. About the Author Enrico Buonanno studied computer science at Columbia University and has 15 years of experience as a developer, architect, and trainer. Table of Contents

PART 1 - CORE CONCEPTS

  • Introducing functional programming
  • Why function purity matters
  • Designing function signatures and types
  • Patterns in functional programming
  • Designing programs with function composition

PART 2 - BECOMING FUNCTIONAL

  • Functional error handling
  • Structuring an application with functions
  • Working effectively with multi-argument functions
  • Thinking about data functionally
  • Event sourcing: a functional approach to persistence

PART 3 - ADVANCED TECHNIQUES

  • Lazy computations, continuations, and the beauty of monadic composition
  • Stateful programs and stateful computations
  • Working with asynchronous computations
  • Data streams and the Reactive Extensions
  • An introduction to message-passing concurrency

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 Enrico Buonanno 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
2017
ISBN
9781638354048

Part 1. Core concepts

In this part we’ll cover the basic techniques and principles of functional programming.
Chapter 1 starts by looking at what functional programming is, and how C# supports programming in a functional style. It then delves deeper into higher-order functions, a fundamental technique of FP.
Chapter 2 explains what pure functions are, why purity has important implications for a function’s testability, and why pure functions lend themselves well to parallelization and other optimizations.
Chapter 3 deals with principles for designing types and function signatures—things you thought you knew but that receive a breath of fresh air when looked at from a functional perspective.
Chapter 4 introduces some of the core functions of FP: Map, Bind, ForEach, and Where (filter). These functions provide the basic tools for interacting with the most common data structures in FP.
Chapter 5 shows how functions can be chained into pipelines that capture the workflows of your program. It then widens the scope to developing a whole use case in a functional style.
By the end of part 1, you’ll have a good feel for what a program written in a functional style looks like, and you’ll understand the benefits that this style has to offer.

Chapter 1. Introducing functional programming

This chapter covers
  • Benefits and tenets of functional programming
  • Functional features of the C# language
  • Representation of functions in C#
  • Higher-order functions
Functional programming is a programming paradigm: a different way of thinking about programs than the mainstream, imperative paradigm you’re probably used to. For this reason, learning to think functionally is challenging but also very enriching. My ambition is that after reading this book, you’ll never look at code with the same eyes as before!
The learning process can be a bumpy ride. You’re likely to go from frustration at concepts that seem obscure or useless to exhilaration when something clicks in your mind, and you’re able to replace a mess of imperative code with just a couple of lines of elegant, functional code.
This chapter will address some questions you may have as you start on this journey: What exactly is functional programming? Why should I care? Can I code functionally in C#? Is it worth the effort?
We’ll start with a high-level overview of what functional programming (FP) is, and how well the C# language supports programming in a functional style. We’ll then discuss functions and how they’re represented in C#. Finally, we’ll dip our feet in the water with higher-order functions, which I’ll illustrate with a practical example.

1.1. What is this thing called functional programming?

What exactly is functional programming? At a very high level, it’s a programming style that emphasizes functions while avoiding state mutation. This definition is already twofold, as it includes two fundamental concepts:
  • Functions as first-class values
  • Avoiding state mutation
Let’s see what these mean.

1.1.1. Functions as first-class values

In a language where functions are first-class values, you can use them as inputs or outputs of other functions, you can assign them to variables, and you can store them in collections. In other words, you can do with functions all the operations that you can do with values of any other type.
For example, type the following into the REPL:[1]
1
A REPL is a command-line interface allowing you to experiment with the language by typing in statements and getting immediate feedback. If you use Visual Studio, you can start the REPL by going to View > Other Windows > C# Interactive. On Mono, you can use the csharp command. There are also several other utilities that allow you to run C# snippets interactively, some even in the browser.
Func<int, int> triple = x => x * 3; var range = Enumerable.Range(1, 3); var triples = range.Select(triple); triples // => [3, 6, 9]
In this example, you start by declaring a function that returns the triple of a given integer and assigning it to the variable triple. You then use Range to create an IEnumerable<int> with the values [1, 2, 3]. You then invoke Select (an extension method on IEnumerable), giving it the range and the triple function as arguments; this creates a new IEnumerable containing the elements obtained by applying the triple function to each element in the input range.
This short snippet demonstrates that functions are indeed first-class values in C#, because you can assign the multiply-by-3 function to the variable triple, and give it as an argument to Select. Throughout the book you’ll see that treating functions as values allows you to write some very powerful and concise code.

1.1.2. Avoiding state mutation

If we follow the functional paradigm, we should refrain from state mutation altogether: once created, an object never changes, and variables should never be reassigned. The term mutation indicates that a value is changed in-place—updating a value stored somewhere in memory. For example, the following code creates and populates an array, and then it updates one of the array’s values in place:
int[] nums = { 1, 2, 3 }; nums[0] = 7; nums // => [7, 2, 3]
Such updates are also called destructive updates, because the value stored prior to the update is destroyed. These should always be avoided when coding functionally. (Purely functional languages don’t allow in-place updates at all.)
Following this principle, sorting or filtering a list should not modify the list in place but should create a new, suitably filtered or sorted list without affecting the original. Type the following into the REPL to see what happens when sorting or filtering a list using LINQ’s Where and OrderBy functions.
Listing 1.1. Functional approach: Where and OrderBy don’t affect the original list
As you can see, the original list is unaffected by the sorting or filtering operations, which yielded new IEnumerables.
Let’s look at a counterexample. If you have a List<T>, you can sort it in place by calling its Sort method.
Listing 1.2. Nonfunctional approach: List<T>.Sort sorts the list in place
var original = new List<int> { 5, 7, 1 }; original.Sort(); original // => [1, 5, 7]
In this case, after sorting, the or...

Índice