Functional Programming in C#
eBook - ePub

Functional Programming in C#

How to write better C# code

Enrico Buonanno

Share book
  1. 408 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Functional Programming in C#

How to write better C# code

Enrico Buonanno

Book details
Book preview
Table of contents
Citations

About This Book

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

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Functional Programming in C# an online PDF/ePUB?
Yes, you can access Functional Programming in C# by Enrico Buonanno in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in C#. We have over one million books available in our catalogue for you to explore.

Information

Publisher
Manning
Year
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...

Table of contents