Functional Programming in C#
eBook - ePub

Functional Programming in C#

How to write better C# code

Enrico Buonanno

Buch teilen
  1. 408 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfĂŒgbar
eBook - ePub

Functional Programming in C#

How to write better C# code

Enrico Buonanno

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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

HĂ€ufig gestellte Fragen

Wie kann ich mein Abo kĂŒndigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kĂŒndigen“ – ganz einfach. Nachdem du gekĂŒndigt hast, bleibt deine Mitgliedschaft fĂŒr den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich BĂŒcher herunterladen?
Derzeit stehen all unsere auf MobilgerĂ€te reagierenden ePub-BĂŒcher zum Download ĂŒber die App zur VerfĂŒgung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die ĂŒbrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den AboplÀnen?
Mit beiden AboplÀnen erhÀltst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst fĂŒr LehrbĂŒcher, bei dem du fĂŒr weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhĂ€ltst. Mit ĂŒber 1 Million BĂŒchern zu ĂŒber 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
UnterstĂŒtzt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nÀchsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Functional Programming in C# als Online-PDF/ePub verfĂŒgbar?
Ja, du hast Zugang zu Functional Programming in C# von Enrico Buonanno im PDF- und/oder ePub-Format sowie zu anderen beliebten BĂŒchern aus Computer Science & Programming in C#. Aus unserem Katalog stehen dir ĂŒber 1 Million BĂŒcher zur VerfĂŒgung.

Information

Verlag
Manning
Jahr
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...

Inhaltsverzeichnis