Introducing Functional Programming Using C# : Leveraging a New Perspective for OOP Developers Vaskaran Sarcar instant download
Introducing Functional Programming Using C# : Leveraging a New Perspective for OOP Developers Vaskaran Sarcar instant download
https://ebookmass.com/product/introducing-functional-
programming-using-c-leveraging-a-new-perspective-for-oop-
developers-vaskaran-sarcar/
https://ebookmass.com/product/introducing-rescript-functional-
programming-for-web-applications-1st-edition-danny-yang/
https://ebookmass.com/product/programming-principles-and-practice-
using-c-second-edition-stroustrup/
https://ebookmass.com/product/data-parallel-c-programming-accelerated-
systems-using-c-and-sycl-james-reinders/
https://ebookmass.com/product/programming-principles-and-practice-
using-c-2nd-edition-ebook-pdf/
Vaskaran Sarcar
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
The will to win, the desire to succeed, the urge to reach your full
potential…these are the keys that will unlock the door to personal
excellence.
Prerequisite Knowledge
The target readers of this book are those who want to make the most of
C# by harnessing the power of functional programming. I expect you to
be familiar with .NET, C#, and OOP concepts. In fact, knowing about
some advanced concepts such as delegates and lambda expressions can
accelerate your learning. I assume that you know how to compile or run
a C# application in Visual Studio. This book does not invest time in
easily available topics, such as how to install Visual Studio on your
system, how to write a “Hello World” program in C#, and so forth.
Though I have used C# as the programming language, if you are familiar
with a similar language like Java, you can apply that understanding to
this book.
Who Is This Book For?
In short, read this book if you answer “yes” to the following questions:
Are you familiar with .NET, C#, and basic object-oriented concepts
such as polymorphism, inheritance, abstraction, and encapsulation?
Are you familiar with some of the advanced concepts in C# such as
delegates, lambda expressions, and generics?
Do you know how to set up your coding environment?
Do you want to develop your functional programming skills?
Are you interested in knowing how the core constructs of C# can
help you in FP?
You probably shouldn’t pick this book if the answer is “yes” to any of
the following questions:
Are you looking for a C# tutorial or reference book?
Are you not ready to experiment with FP with a programming
language that was primarily developed for OOP?
Do you despise Windows, Visual Studio, or .NET?
Useful Software
These are the important tools that I use in this book:
While writing this book, I had the latest edition of Visual Studio
Community 2022 (64-bit, version 17.5.4). All the programs were
tested with C# 11 and .NET 7.
Nowadays the C# language version is automatically selected based
on your project’s target framework(s) so that you can always get the
highest compatible version by default. In the latest versions, Visual
Studio doesn’t allow the UI to change the value, but you can change it
by editing the .csproj file.
As per a new rule, C# 11 is supported only on .NET 7 and newer
versions. C# 10 is supported only on .NET 6 and newer versions. C# 9
is supported only on .NET 5 and newer versions. C# 8.0 is supported
only on .NET Core 3.x and newer versions. If you are interested in the
C# language versioning, you can visit
https://docs.microsoft.com/en-
us/dotnet/csharp/language-reference/configure-
language-version.
The community edition is free of cost. If you do not use the Windows
operating system, you can still use the free Visual Studio Code, which
is a source-code editor developed by Microsoft to support Windows,
Linux, or Mac operating systems. At the time of this writing, Visual
Studio 2022 for Mac is also available, but I did not test my code on it.
Note At the time of this writing, this link works fine and the
information is correct. But the link and policies may change in the
future. The same comment applies to all the links mentioned in this
book.
Source Code
All the source code used in this book can be found at
https://github.com/apress/introduction-functional-
programming-cs.
Final Words
Congratulations, you have chosen a programming language to
experiment with a paradigm that will assist you throughout your
career. As you learn and review these concepts, I suggest you write your
code instead of copying and pasting it; there is no better way to learn.
Upon completing this book, you’ll be confident about FP and the
value it provides you.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit https://www.apress.com/gp/services/source-code.
Acknowledgments
I thank the Almighty. I sincerely believe that only with His blessings
could I complete this book. I also extend my deepest gratitude and
thanks to the following people:
Leandro Fernandes Vieira and Paul Louth: They allowed me to use
the Curryfy library and language-ext library in this book. Leandro
also joined the technical review team and provided many useful
suggestions and improvements for this book.
Shekhar Kumar Maravi: Shekhar was another technical reviewer
for this book. He has been reviewing my books since 2015. Whenever
I am in need, he provides me with support. Thank you one more time.
Smriti, Laura, and Mark: Thanks to each of you for giving me
another opportunity to work with you and Apress.
Shon, Kim, Nagarajan, and Vinoth: Thanks to each of you for your
exceptional support to improve my work.
Finally, I thank those people from the functional programming
community who have shared their knowledge through online blogs,
articles, courses, and books.
Table of Contents
Part I: Getting Familiar with Functional Programming
Chapter 1:Functional Programming Overview
C# Supports Multiple Paradigms
Functions and Methods Are Equivalent in C#
Important Characteristics of FP
FP Treats Functions as First-Class Citizens
FP Prefers Immutability
FP Prefers Pure Functions
FP Follows a Declarative Style
FP vs.OOP
FP Benefits
Exercises
Summary
Solutions to Exercises
Chapter 2:Understanding Functions
Mathematical Background of Functions
Mathematical Functions vs.C# Functions
Representing Functions in C#
Using Static Methods
Using Delegates and Lambdas
Using a Dictionary
Built-in Delegates Are Important
Higher-Order Function
Custom HOF
Built-in HOF
First-Order Function
Refactoring Impure Functions
Program with Impurities
Removing Impurities
Exercises
Summary
Solutions to Exercises
Chapter 3:Understanding Immutability
What Is Immutability?
Immutable Objects in .NET
Reviewing Mutable Types
Programming with a Mutable Type
The Path Toward Immutability
Achieving External Immutability
Enforcing Internal Immutability
Better Code Using Modern Features
More on Immutability
Understanding Shallow Immutability
Searching for a Solution
Making a Better Solution
Implementing Popsicle Immutability
Exercises
Summary
Solutions to Exercises
Part II: Harnessing the Power of Functional Programming
Chapter 4:Composing Functions Using Pipelining
Overview
Coding Functional Composition
Importance of Chaining Functions
Program Without Chaining Functions
Refactoring Using Chaining Functions
Applying Composition
Using Pipelining
Using HOFs
Exercises
Summary
Solutions to Exercises
Chapter 5:Composing Functions Using Currying
Overview of Currying
Program Without Currying
Using the Concept of Currying
Using External NuGet Packages
Using Curryfy
Exercises
Summary
Solutions to Exercises
Chapter 6:Handling Temporal Coupling
Temporal Coupling Overview
How Does This Happen?
Recognizing the Problem
A Program That Suffers from Temporal Coupling
Removing the Effect
A Better Program
Exercises
Summary
Solutions to Exercises
Chapter 7:Functional Patterns
Map Pattern
Understanding the Problem
Initial Solution
Better Solution
Concise Solution
Select As Map
Introducing Functors
Conclusion
Bind Pattern
Understanding the Problem
Initial Solution
FP-Based Solution
SelectMany As Bind
What About Monads?
Conclusion
Filter Pattern
Understanding the Problem
Initial Solution
Where As Filter
Fold Pattern
Understanding the Problem
Solutions Using Built-in Functions
Conclusion
Revisiting ForEach
Exercises
Summary
Solutions to Exercises
Chapter 8:Exception Handling
Reviewing Exception Handling in OOP
Imperative Style of Programming
Exception Handling in FP
Using language-ext
Introducing the Either Type
Handling a Single Exception
Handling Multiple Exceptions
Chaining Exceptions
Handling Null Values
Introducing the Option Type
Exercises
Summary
Solutions to Exercises
Chapter 9:Miscellaneous Topics
Helpful Features for FP
Delegates and Lambdas
Anonymous Methods
Extension Methods and LINQ
Type Inference
Importing Static Members
Immutability Features
Expression-Bodied Members
Local Functions
Tuples
Pattern Matching
Revisiting Option<T>
Bind Function
Return Function
Introducing Monads
Definition
Mathematical Background
Monad Laws
Chaining Multi-argument Functions
Final Suggestions
Command Query Separation
Learn Design Patterns and Anti-Patterns
Don’t Let Failures Stop You
How Much Functional Code Do I Need?
Applications of FP
The Road Ahead
Exercises
Summary
Solutions to Exercises
Appendix:Recommended Resources
Index
About the Author
Vaskaran Sarcar
obtained his master’s degree in software
engineering from Jadavpur University,
Kolkata (India), and his master’s of
computer application from Vidyasagar
University, Midnapore (India). He was a
National Gate Scholar (2007–2009) and
has more than 12 years of experience in
education and the IT industry. He
devoted his early years (2005–2007) to
the teaching profession at various
engineering colleges, and later he joined
HP India PPS R&D Hub in Bangalore. He
worked at HP until August 2019. At the
time of his retirement from HP, he was a senior software engineer and
team lead. Vaskaran is following his passion and is now a full-time
author. You can find him on LinkedIn at
https://www.linkedin.com/in/vaskaransarcar and see all
of his books at
https://amazon.com/author/vaskaran_sarcar.
About the Technical Reviewers
Leandro Fernandes Vieira
is a senior software engineer currently
working for a leading payment solutions
company. He earned his degree in system
analysis and development from Sã o
Paulo State Technological College
(FATEC-SP), Brazil. His realm of
expertise includes the .NET stack and the
C# and F# programming languages. He
has a passion for programming and
algorithms and likes to contribute to
open-source projects; in fact, he is a
creator of the RecordParser project, one
of the fastest CSV parsers for .NET.
He enjoys spending time with his family, walking in the park, hitting
the gym, and listening to heavy-metal music.
You can reach him at https://github.com/leandromoh/.
So, using C#, you can also combine different styles of coding in an
application. Most importantly, to implement the key ideas in functional
programming (FP), you can use C# instead of learning a new
programming language. Throughout the book, we’ll look into these
possibilities.
Q&A Session
1.1 C# primarily follows OOP, but you are using it in the functional
style. This helps us avoid learning a new programming language,
but are you saying that learning an FP-based computer language is
a bad idea?
Not at all. Developing your knowledge and learning a new
programming language are always good ideas. If you know functional
languages like F# or Haskell, no one is restricting you from using them.
But in a real-world project, you may not have that freedom. For
example, if you are working on a project that uses only C#, you have
only one option: coding with C#. But C# is a multiparadigm language,
and it supports functional programming. This means that by using
some of its features, you can bring the power of functional
programming to an existing project.
Second, you may not have the time or motivation to learn a new
programming language to fulfill some specific needs in a project. In
such cases, it is always helpful to implement the concept using known
features.
Finally, many existing features in C# have been developed following
the functional style of coding. Instead of blindly using them, if you
understand the context, you can enjoy your learning.
Important Characteristics of FP
Though FP is a programming paradigm, it does not specify how the
concepts should be implemented in a programming language. As a
result, a programming language that follows FP can support many
different features to implement these concepts. At a high level, FP has
the following characteristics:
It treats functions as first-class citizens.
It prefers immutability.
It prefers pure functions.
It follows declarative programming.
Let’s take a quick look at these bullet points. You can surely guess
that we’ll cover all these points in more detail in the upcoming
chapters.
Demonstration 1
In the following program, doubleMaker is an instance of Func<int,
int>, and it is used as a variable. I pass this variable to another
function, called GetResult.
int temp = 5;
Func<int, int> doubleMaker = x => x * 2;
int result =
Container.GetResult(doubleMaker,temp);
WriteLine(result);
Output
The output is easy to predict. Since I have passed the integer 5 as an
input (along with the function variable doubleMaker), the program
outputs 10.
Analysis
Let’s analyze the key steps in this program. First I declare a function
using a delegate and name the function variable doubleMaker. I then
pass this variable to invoke the GetResult function. So, the following
points are clear:
You can assign a function to a variable.
You can pass a function as an argument to another function.
As you progress more with learning FP, it will be natural for you to
use functions as return types or store them in a data structure. So, we
can conclude that C# indeed supports first-class functions.
FP Prefers Immutability
Immutability is a design choice, and it is one of the fundamental
principles of FP. In this context, I’d like to quote Microsoft again. The
online link https://learn.microsoft.com/en-
us/archive/msdn-magazine/2010/april/fsharp-basics-
an-introduction-to-functional-programming-for-net-
developers says the following:
Demonstration 2
Suppose I have a program that starts with a list of names. Later, I clear
the content of this list and add new names. The following program
demonstrates this:
Note Removing the lambda expression, you can simply the line
names.ForEach(x => WriteLine(x)); as
names.ForEach(WriteLine);.
Output
Let’s verify the output.
Q&A Session
1.2 How does immutability fit into functional programming?
Immutability prevents nasty bugs from implicit dependencies,
destructive updates, and state mutations. These are aligned with FP’s
goal. Immutable types are thread-safe; therefore, in a multithreaded
environment, they make your programming life easy. Shortly, you’ll
learn about pure functions and side effects. Then you’ll understand that
these immutable types can help you avoid side effects too. In Chapter 6,
you’ll see that immutable types are also useful to avoid temporal
coupling. There are many more benefits; once you finish this book,
you’ll be able to find those benefits in other areas as well.
Demonstration 3
To answer the previous question (1.3), I’m going to modify
Demonstration 2. Let’s assume that the program needs to display the
names along with the number of characters that are present in the
name. The following is a typical implementation that contains a
possible bug. Why is there a possible bug? I start with a list of names
called names, and then I use the following code segment in this
program:
Output
Here is some sample output when everything goes well and it was able
to add a new name successfully:
Analysis
This program shows that a destructive update can raise a runtime error.
As developers, we do not like to see a program crash at runtime. FP’s
philosophy is simple: avoid destructive updates. When I discuss
immutability in depth in Chapter 3, you’ll see that we can avoid this
kind of update in our program.
Demonstration 4
You will learn more about purity and side effects shortly. For now, it will
be sufficient if you understand the following program:
WriteLine(AddFiveTo(2));
WriteLine(GetRandomNumber(2));
Output
Here are some probable outputs from this program:
Sample Output-1:
7
3
Sample Output-2:
7
6
Sample Output-3:
7
4
And so on. You can see that given input 2, GetRandomNumber
returns different values. Since the result is inconsistent, you can
conclude that this is an impure function.
Now, look into the AddFive function. You can see that AddFiveTo
is consistent; it always returns 7 if the input is 2. You can also see that
this function depends on the supplied input only; it does not change
any variables or data of any type outside of the function. So, this
function does not have any side effect. Since both conditions for purity
are satisfied, we can conclude that AddFiveTo is a pure function.
class Sample
{
public static int GetResult(int a)
{
int random = new Random().Next(0,2);
return a / random;
}
}
The first problem is obvious: you cannot predict the result in
advance. For example, the following line:
can give you valid data, or it can raise the following exception (when
the divisor random becomes 0):
System.DivideByZeroException: 'Attempted to divide
by zero.'
Throwing an exception always forces you to think about gracefully
handling the exception; otherwise, your program crashes, which is an
example of the worst possible side effect. In fact, exceptions indicate
indeterminism in the code.
I discuss case 4 in the section “Functions with I/O,” which is coming
next.
Console.WriteLine("Enter a number:");
Did you notice that the state of the system has changed, and
returning the system to its previous state is impossible now? You can
see that when a function needs to depend on the external world, there
is no escape. You may argue that this is an intended scenario, but
following the FP paradigm, it is still considered a side effect. In fact, a
purely mathematical function often needs to communicate the result
using the I/O. So, some of your code segments will have to be impure.
Now the next question is, which part of the code segments can be
impure? A common guideline for this type of situation is that you
should try to separate the functions that perform the I/O from the
functions that perform the actual computation. The functions that
perform those computations should be the pure function in the
functional world. In C#, we can mix them, but to follow a functional
style of coding, keep this suggestion in your mind.
In this book, I often compare OOP-style coding with an equivalent
functional style of coding with complete programs. When I refactor the
imperative code to functional code, I focus on the key aspects. Normally,
I do not change the Main method (aka function) that handles the I/O
operations. Remember, since I use top-level statements to demonstrate
programs, you will not explicitly see the presence of the Main method.
For example, in .NET 7, I can run a program that consists of a single line
as follows:
Console.WriteLine("Hello, reader!");
POINT TO NOTE
In the OOP style, it is a common practice to encapsulate data and
methods inside a class. But in the functional style of coding, it is
common to separate the functions from the data. The discussion of
side effects should give you the idea that FP encourages us to work
on pure functions and minimize the side effects.
POINT TO REMEMBER
In the context of purity and side effects, you can remember the
following points:
Any side effect indicates a visible “state change” of a program.
A pure function is “pure” to some extent. We cannot avoid all
possible circumstances. For example, during an execution of a C#
function, an exception can be thrown because of various factors.
Typical examples include insufficient memory or any other
operating system errors.
This means we cannot control every possible side effect. In
general, you should focus on those parts that you can control.
Finally, you should not conclude that an impure function is a bad
thing. In OOP, you probably have seen that we want dynamic
behavior in many applications, and that behavior is very much
desirable there. In fact, a normal program that tries to update a
database has a “desirable” side effect. Here we are studying pure
functions following the formal definitions, and this is the reason
we are focusing on purity. As you progress on this topic, these
topics will be clearer to you.
Q&A Session
1.4 Why does FP like pure functions?
There are many reasons behind this. Let me show you some of those
benefits:
Since these functions result in the same output, you can write test
cases against a consistent or reliable output.
This consistent nature can provide you with huge benefits when you
focus on parallelization.
In fact, once you get the result from an execution of a pure function,
you can avoid the further execution of this function. This is because,
once computed, this computed value will not change anymore.
Demonstration 5
I will now show you a sample program that follows an imperative style
of coding. OOP developers are quite familiar with this style. Given a list
of numbers, the following program picks the numbers that are greater
than 30 (notice the important segment in bold):
Output
This program produces the following output:
Demonstration 6
Here is the refactored program (notice the important changes in bold):
Output
It should be no surprise that you see an equivalent output (that you saw
in Demonstration 5):
Q&A Session
1.6 You said that FP developers prefer the declarative style of
coding. Do you think that the declarative style is better than the
imperative style?
No. Each approach has its pros and cons. Remember that our goal is to
take the best from each approach.
Let’s see the advantages of the declarative style of coding. The
imperative style instructs how to perform the computation, so the
order of execution of the statements is important. But the declarative
style focuses on what to be computed, not on “how it’s to be computed.”
So, it helps you vary the function invocation calls. For example,
given the list shown in the previous demo, each of the following code
segments (segment-1 and segment-2) will produce the identical result
(notice that I have altered the function calls in the top two lines in these
segments):
// Segment-1
numbers.Where(x => x > 30)
.Select(x => x)
.ToList()
.ForEach(x => Write(x + "\t"));
// Segment-2
numbers.Select(x => x)
.Where(x => x > 30)
Other documents randomly have
different content
The Project Gutenberg eBook of The Life of
Captain Sir Richard F. Burton, volume 1 (of 2)
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Language: English
BY HIS WIFE,
ISABEL BURTON.
WITH NUMEROUS PORTRAITS,
ILLUSTRATIONS, AND MAPS.
IN TWO VOLUMES.
VOL. I.
CONSECRATION.
TO MY EARTHLY MASTER,
FOREWORD.
"No man can write a man down except himself."
Note.—I must beg the reader to note, that a word often has several
different spellings, and my husband used to give them a turn all
round. Indeed, I may say that during the latter years of his life he
adopted quite a different spelling, which he judged to be correcter.
In many cases it is caused by the English way of spelling a thing,
and the real native way of spelling the same. For English Meeanee,
native way Miani. The battle of Dabba (English) is spelt Dubba,
Dubbah, by the natives. Fulailee river (English) is spelt Phuleli
(native). Mecca and Medina have sometimes an h at the end of
them. Karrachee is Karáchi. Sind is spelt Sind, Sindh, Scind, Scinde;
and what the Anglo-Indians call Bóbagees are really Babárchis, and
so on. I therefore beg that the spelling may not be criticized. In
quoting letters, I write as the author does, since I must not change
other people's spelling.—I. B.
[Transcriber's Note.—The page headings of the original edition have been converted into
sidenotes in this digital edition. Typographical and other obvious errors have also been
corrected, but the variations in the spelling of proper names, etc., mentioned above
remain.]
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
ebookmasss.com