Introducing Functional Programming Using C# : Leveraging a New Perspective for OOP Developers Vaskaran Sarcar 2024 Scribd Download
Introducing Functional Programming Using C# : Leveraging a New Perspective for OOP Developers Vaskaran Sarcar 2024 Scribd Download
https://ebookmass.com
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/
testbankdeal.com
https://ebookmass.com/product/programming-principles-and-practice-
using-c-second-edition-stroustrup/
testbankdeal.com
https://ebookmass.com/product/data-parallel-c-programming-accelerated-
systems-using-c-and-sycl-james-reinders/
testbankdeal.com
https://ebookmass.com/product/programming-principles-and-practice-
using-c-2nd-edition-ebook-pdf/
testbankdeal.com
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.
Visit https://ebookmass.com
now to explore a rich
collection of eBooks and enjoy
exciting offers!
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
Visit https://ebookmass.com
now to explore a rich
collection of eBooks and enjoy
exciting offers!
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
Random documents with unrelated
content Scribd suggests to you:
Fitz-Empress: a policy of steady loyalty to the lawful authority of the
French Crown, against which the counts of Blois lived in perpetual
opposition. After Robert’s death, in 1031, Fulk appeared in the
unexpected character of peace-maker between Queen Constance
and her son, the young King Henry, whom she was trying to oust
from his throne;[359] and he afterwards accompanied Henry on an
expedition to dislodge Odo of Champagne from Sens, which
however succeeded no better than the attempt once made by Odo
and Henry to dislodge Fulk himself from Amboise.[360] But peace or
war, it mattered not to the Black Count; he was never at a loss for
work. When there was no enemy to fight or to outwit, his versatile
energies flung themselves just as readily into the encouragement of
piety or the improvement and embellishment of his capital. Over the
black bastions of the castle with which the French King Philip
Augustus, when he had wrested Angers from a degenerate
descendant of its ancient counts, found it needful to secure his hold
on “this contemptuous city,” there still looks out upon the river a
fragment of a ruined hall, chiefly of red flintstone; it is the sole
remains of the dwelling-place of Fulk Nerra—in all likelihood, his own
work.[361] A poetic legend shows him to us for once quietly at home,
standing in that hall and gazing at the view from its windows. At his
feet flowed the purple Mayenne between its flat but green meadows
—for the great suburb beyond the river did not yet exist—winding
down beneath a bridge of his own building to join the Loire beyond
the rising hills to the south-west. His eyes, keen as those of the
“Falcon” whose name he bore, reached across river and meadow to
the slope of a hill directly opposite him, where he descried a dove
flying to and fro, picking up fragments of earth and depositing them
in a cavity which it seemed to be trying to fill. Struck by the bird’s
action, he carefully marked the spot, and the work of the dove was
made the foundation-stone of a great abbey in honour of S. Nicolas,
which he had vowed to build as a thank-offering for deliverance from
a storm at sea on his return from his second pilgrimage.[362] This
abbey, with a nunnery founded near it eight years later—in 1128—by
his countess Hildegard, on the site of an ancient church dedicated to
our Lady of Charity,[363] became the nucleus round which gathered
in after-years a suburb known as Ronceray, scarcely less important
than the city itself. These tranquil home-occupations, however, could
not long satisfy the restless temper of Fulk. The irresistible charm
exercised by the Holy Land over so many of the more imaginative
spirits of the age drew him to revisit it in 1035. One interesting event
of the journey is recorded: his meeting at Constantinople with Duke
Robert of Normandy, father of William the Conqueror.[364] The old
and the young penitent completed their pilgrimage together; but only
the former lived to see his home again; and when he reached it, he
found the gates of Angers shut in his face by his own son. The
rebellion was soon quelled. Saddled and bridled like a beast of
burthen, Geoffrey came crawling to his father’s feet. “Conquered art
thou—conquered, conquered!” shouted the old count, kicking his
prostrate son. “Aye, conquered by thee, for thou art my father; but
unconquered by all beside!” The spirited answer touched Fulk’s
paternal pride, and Geoffrey arose forgiven.[365] The power which he
had thus undutifully tried to usurp was soon to be his by right; not,
however, till the Black Count had given one last proof that neither his
hand nor his brain had yet forgotten its cunning. Odo of Champagne
had long ago left Touraine to its fate, and for the last four years he
had been absorbed in a visionary attempt to wrest from the Emperor
Conrad II., first the kingdom of Burgundy, then that of Italy, and at
last the imperial crown itself; while Fulk’s conquests of the valleys of
the Indre and the Cher had been completed by the acquisition of
Montbazon and St.-Aignan.[366] When at the close of 1037 tidings
came that Odo had been defeated and slain in a battle with the
imperial forces at Bar, the Angevin at once laid siege to Langeais,
and took it.[367] One more stronghold still remained to be won in the
valley of the Vienne. From the right bank of the little river, winding
down silvery-blue between soft green meadows to join the Loire
beyond the circle of the distant hills to the north-west, the mighty
steep of Chinon rises abruptly, as an old writer says, “straight up to
heaven”; range upon range of narrow streets climb like the steps of a
terrace up its rocky sides; acacias wave their bright foliage from
every nook; and on the crest of the ridge a long line of white ruins,
the remains of a stately castle, stand out against the sky. A dense
woodland of oaks and larches and firs, stretching north-eastward
almost to the valley of the Indre, and crowded with game of every
kind, formed probably no small part of the attractions which were to
make Chinon the favourite retreat of Fulk Nerra’s greatest
descendant. In those ruined halls, where a rich growth of moss and
creepers has replaced the tapestried hangings, earlier and later
memories—memories of the Black Count or of the Maid of Orleans—
seem to an English visitor only to flit like shadows around the death-
bed of Henry Fitz-Empress. But it was Fulk who won Chinon for the
Angevins. The persuasion of his tongue, as keen as his sword,
sufficed now to gain its surrender.[368] The Great Builder’s work was
all but finished; only the keystone remained to be dropped into its
place. Tours itself stood out alone against the conqueror of Touraine.
One more blow, and the count of Anjou would be master of the
whole valley of the Loire from Amboise to the sea.
[365] Will. Malm. Gesta Reg., l. iii. c. 235 (Hardy, pp. 401,
402).
[368] Ibid.
[380] Origo Com. Vindoc., in Rer. Gall. Scriptt., vol. xi. p. 31.
See also Mabillon, Ann. Bened., vol. iv. pp. 378, 379.
[391] Will. Malm. Gesta Reg., l. iii. c. 231 (Hardy, p. 395). Cf.
Will. Poitiers (Duchesne, Hist. Norm. Scriptt.), p. 182.
Then Geoffrey threw off the mask. William had no children; his
next heir was his half-brother Odo, the son of his father’s second
marriage with Brisca, heiress of Gascony.[392] But after Brisca’s
death, William the Great had married a third wife, whom he had left a
still young widow with three little children. Before William the Fat had
been many months dead, his stepmother the widowed Countess
Agnes gave her hand to Geoffrey of Vendôme.[393] Geoffrey’s motive
is plain; he sought to prevent the union of Poitou and Gascony and
to get the former practically into his own hands as stepfather and
guardian to the young sons of Agnes. But in Anjou the wedding gave
great scandal; Geoffrey and Agnes were denounced in the harshest
terms as too near akin to marry.[394] They seem in fact to have been,
by the reckoning of the canon law, cousins in the third degree, as
being, one a grandson, the other a great-granddaughter of Adela of
Chalon, the second wife of Geoffrey Greygown.[395] At any rate they
were looked upon as sinners, and by no one more than the
bridegroom’s father. The whole scheme of Geoffrey’s meddlings in
Aquitaine was repugnant to Fulk Nerra’s policy; he looked to his son
to complete his own labours in Touraine and Maine, and it was no
good omen for the fulfilment of his hopes when Geoffrey thus turned
his back upon his appointed work for the love of Countess Agnes or
of her late husband’s possessions. The capture of William the Fat
had been the signal for the first outbreak of a “more than civil war”
between father and son;[396] Geoffrey’s misconduct during his
regency in Anjou brought matters to the crisis which ended in his first
and last public defeat. Nevertheless he obstinately pursued his
projects. The Poitevins, by the death of their count, were left, as their
own chronicler says, “as sheep having no shepherd”; there was a
party among them ready to support the claims of Agnes’s sons
against their elder half-brother Odo of Gascony; and one of the
leaders of this party, William of Parthenay, built with Angevin help a
fortress at Germont in which he held out successfully against the
besieging forces of Odo. The count of Gascony then proceeded to
Mausé, another stronghold of his enemies, and in assaulting this
place he was slain.[397] He left no children; the elder of Geoffrey
Martel’s stepsons was now therefore heir to Poitou. The boys were
twins; the third child of Agnes was a girl, who bore her mother’s
name, and for whom her mother and stepfather contrived in 1043 to
arrange a marriage with no less important a personage than the
Emperor Henry III.,[398] whose first wife had been a daughter of
Cnut. It was not till the year after this imperial wedding that the
troubled affairs of Aquitaine were definitely settled. In 1044 Countess
Agnes came to Poitiers accompanied by her two sons, Peter and
Geoffrey, and her husband, their stepfather, Geoffrey Martel; there
they held with the chief nobles of Poitou a council at which Peter, or
William as he was thenceforth called, was solemnly ordained as
duke of Aquitaine, and his brother sent into Gascony to become its
count.[399] Agnes at least must now have attained her object;
whether Geoffrey Martel was equally satisfied with the result of his
schemes may be a question, for we do not clearly know how wide
the range of those schemes really was. If, as seems likely, they
included the hope of acquiring a lasting hold over Aquitaine, then
their issue was a failure. By the victory of Montcontour Geoffrey had
gained for himself at one blow a great military reputation; but for
Anjou the only solid gain was the acquisition of Saintonge, and this,
like some of the outlying possessions of the house of Blois, soon
proved more trouble than profit. If Martel expected that his stepsons
would hold themselves indebted to him for their coronets and remain
his grateful and dutiful miscalculation. The marriage of a duchess-
dowager of Aquitaine with Geoffrey Martel naturally suggests
thoughts of the marriage of a duchess-regnant with a later count of
Anjou; but the resemblance between the two cases is of the most
superficial kind; the earlier connexion between Anjou and Aquitaine
did little or nothing to pave the way for their later union. Geoffrey
himself, indeed, had already discovered that although the count of
Vendôme might go seeking adventures in the south, the duties and
the interests of the count of Anjou still lay to the north, or at the
utmost no farther away than the banks of the great frontier-river.
[400] Hugh of Fleury, Rer. Gall. Scriptt., vol. xi. p. 159. Chron.
Fr. Andreæ, ib. p. 364.
[402] Hist. Franc. Fragm. (Rer. Gall. Scriptt., vol. xi.), p. 160.
Hugh of Fleury (ibid.), p. 159.
[403] Chron. Virdun. a. 1039 (Rer. Gall. Scriptt., vol. xi. p. 144).
R. Glaber, l. v. c. 2 (ib. vol. x. p. 60), copied in Gesta Cons.
(Marchegay, Comtes), pp. 122, 123. Fulk Rechin (ibid.), p. 378.
When the great English scholar and the great Emperor who had
brought him into Gaul were gone, Tours underwent her full share of
suffering in the invasions of the northmen. City and abbey became to
the valley of the Loire something like what Paris and S. Denis were
to that of the Seine, the chief bulwark against the fresh tide of
heathen force which threatened to sweep away the footsteps of
saints and scholars. Once, indeed, Tours had been in danger from
heathens of another sort, and a body of Saracens had been turned
back from her gates and destroyed by Charles Martel.[414] There
was no Martel to save her from the northmen; her only defence
consisted in the valour of her citizens, and the fortifications left to her
by her Roman governors and carefully strengthened by her
Karolingian sovereigns.[415] Over and over again the pirates were
driven back from the walls of Cæsarodunum; over and over again S.
Martin’s Abbey was burnt to the ground. For years the canons, who
in Alcuin’s days had taken the place of the original monks,[416] lived
in constant fear of desecration befalling their patron’s body, and
carried it from place to place, like the body of our own S. Cuthbert,
sometimes depositing it within the city walls, sometimes removing it
farther inland—once even to the far-off Burgundian duchy—bringing
it home whenever they dared, or whenever they had a church fit to
contain it. Two of these “reversions”—one on December 13, 885, the
other on May 12, 919—were annually celebrated at Tours, in addition
to two other feasts of S. Martin, his ordination on July 4 and his
“deposition” on November 11.[417] In the first reversion Ingelger, the
founder of the Angevin house, was said to have borne a prominent
part. The story of the second was afterwards superseded by a
famous legend known as that of the “subvention of S. Martin.” Once,
it was said, when the citizens of Tours were sore pressed by the
besieging hosts of the northmen, they resolved to intrust their cause
to a heavenly champion, and brought out upon the walls the corpse
of the saint, which had been deposited for safety within the city. The
living heathen fled at once before the dead saint; they were pursued
by the triumphant citizens, still carrying their patron in their midst,
and utterly routed at a spot which thence received the name of “S.
Martin of the Battle.”[418] This story seems to belong to the siege of
903, when Marmoutier was destroyed, and the abbey of S. Martin
burnt to the ground for the third time. When the canons again rebuilt
it, they took the precaution of encircling it with a wall, and procured
from Charles the Simple a charter which resulted in the creation of a
new fortified borough, exempt from the jurisdiction of both bishop
and count, and subject only to its own abbot—in other words, to the
duke of the French, who from the middle of the eighth century
always held in commendam the abbey of S. Martin at Tours, as he
did that of S. Denis at Paris.[419] Thus, side by side with the old city
of the Turones, Cæsarodunum with its Roman walls, its count, its
cathedral and its archbishop, there arose the “Castrum Novum,”
Châteauneuf, “Castellum S. Martini,” Martinopolis as it is sometimes