Functional Programming in C#
eBook - ePub

Functional Programming in C#

How to write better C# code

Enrico Buonanno

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

Functional Programming in C#

How to write better C# code

Enrico Buonanno

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul 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

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 Enrico Buonanno 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
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...

Indice dei contenuti