Complete Functional Programming in C#: How To Write Better C# Code 1st Edition Enrico Buonanno PDF For All Chapters
Complete Functional Programming in C#: How To Write Better C# Code 1st Edition Enrico Buonanno PDF For All Chapters
com
https://textbookfull.com/product/functional-
programming-in-c-how-to-write-better-c-code-1st-
edition-enrico-buonanno/
https://textbookfull.com/product/effective-c-an-introduction-to-
professional-c-programming-1st-edition-robert-c-seacord/
textbookfull.com
https://textbookfull.com/product/learn-c-by-example-covers-
versions-11-to-23-final-release-1-converted-edition-frances-buontempo/
textbookfull.com
https://textbookfull.com/product/hepatology-a-clinical-textbook-10th-
edition-stefan-mauss/
textbookfull.com
The Regulatory Regime of Food Safety in China: Governance
and Segmentation 1st Edition Guanqi Zhou (Auth.)
https://textbookfull.com/product/the-regulatory-regime-of-food-safety-
in-china-governance-and-segmentation-1st-edition-guanqi-zhou-auth/
textbookfull.com
https://textbookfull.com/product/roland-barthes-cinema-1st-edition-
philip-watts/
textbookfull.com
https://textbookfull.com/product/live-from-nicaragua-uprising-or-coup-
a-reader-various/
textbookfull.com
https://textbookfull.com/product/keyness-evolutionary-spirit-a-
philosophical-journey-through-his-work-1st-edition-munoz-bandala/
textbookfull.com
A Doctorate and Beyond: Building a Career in Engineering
and the Physical Sciences 1st Edition Graham C. Goodwin
https://textbookfull.com/product/a-doctorate-and-beyond-building-a-
career-in-engineering-and-the-physical-sciences-1st-edition-graham-c-
goodwin/
textbookfull.com
Functional Programming in C#: How to
write better C# code
Enrico Buonanno
Copyright
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity. For
more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any
form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning Publications
was aware of a trademark claim, the designations have been printed in initial caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to
have the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15 percent recycled and processed without the use of elemental
chlorine.
ISBN 9781617293955
1 2 3 4 5 6 7 8 9 10 – EBM – 22 21 20 19 18 17
Dedication
To the little monkey...
Brief Table of Contents
Copyright
Table of Contents
Preface
Acknowledgments
1. Core concepts
2. Becoming functional
3. Advanced techniques
Chapter 11. Lazy computations, continuations, and the beauty of monadic composition
Index
List of Figures
List of Tables
List of Listings
Table of Contents
Copyright
Table of Contents
Preface
Acknowledgments
1. Core concepts
Exercises
Summary
Exercises
Summary
objects
3.2.1. Primitive types are often not specific enough
3.3.2. Bridging the gap between Action and Func with Unit
Exercises
Summary
Introducing functors
Exercises
Summary
Summary
2. Becoming functional
Exercises
Summary
7.5.2. Modularity in FP
Exercises
Summary
Exercises
Summary
Exercises
Summary
Chapter 10. Event sourcing: a functional approach to persistence
domain?Summary
3. Advanced techniques
Chapter 11. Lazy computations, continuations, and the beauty of monadic composition
Summary
Summary
13.3. Combining asynchrony and validation (or any other two monadic effects)
Summary
Summary
Summary Epilogue:
what next?
List of Figures
List of Tables
List of Listings
Preface
Today, functional programming (FP) is no longer brooding in the research departments of
universities; it has become an important and exciting part of mainstream programming. The
majority of the languages and frameworks created in the last decade are functional, leading some
to predict that the future of programming is functional. Meanwhile, popular object-oriented
languages like C# and Java see the introduction of more functional features with every new
release, enabling a multiparadigm programming style.
And yet, adoption in the C# community has been slow. Why is this so? One reason, I believe, is
the lack of good literature:
Most FP literature is written in and for functional languages, especially Haskell. For
developers with a background in OOP, this poses a programming-language barrier to
learning the concepts. Even though many of the concepts apply to a multiparadigm
language like C#, learning a new paradigm and a new language at once is a tall order.
Even more importantly, most of the books in the literature tend to illustrate functional
techniques and concepts with examples from the domains of mathematics or computer
science. For the majority of programmers who work on line-of-business (LOB)
applications day in and day out, this creates a domain gap and leaves them wondering how
relevant these techniques may be for real-world applications.
These shortcomings posed major stumbling blocks in my own path to learning FP. After tossing
aside the n-th book that explained something known as currying by showing how the add
function can be curried with the number 3, creating a function that can add 3 to any number (can
you think of any application where this would be even remotely useful?), I decided to pursue my
own research path. This involved learning half a dozen functional languages (some better than
others), and seeing which concepts from FP could be effectively applied in C# and in the kind of
applications most developers are paid to write, and it culminated in the writing of this book.
This book bridges the language gap for C# developers by showing how you can leverage
functional techniques in this language. It also bridges the domain gap by showing how these
techniques can be applied to typical business scenarios. I take a pragmatic approach and cover
functional techniques to the extent that they’re useful in a typical LOB application scenario, and
dispense with most of the theory behind FP.
Ultimately, you should care about FP because it gives you the following:
Power— This simply means that you can get more done with less code. FP raises the level
of abstraction, allowing you to write high-level code while freeing you from low-level
technicalities that add complexity but no value.
Safety— This is especially true when dealing with concurrency. A program written in the
imperative style may work well in a single-threaded implementation but cause all sorts of
bugs when concurrency comes in. Functional code offers much better guarantees in
concurrent scenarios, so it’s only natural that we’re seeing a surge of interest in FP in the
era of multicore processors.
Clarity— We spend more time maintaining and consuming existing code than writing new
code, so it’s important that our code be clear and intention-revealing. As you learn to think
functionally, achieving this clarity will become more natural.
If you’ve been programming in an object-oriented style for some time, it may take a bit of effort
and willingness to experiment before the concepts in this book come to fruition. To make sure
learning FP is an enjoyable and rewarding process, I have two recommendations:
Be patient— You may have to read some sections more than once. You may put the book
down for a few weeks and find that when you pick it up again, something that seemed
obscure suddenly starts to make sense.
Experiment in code— You won’t learn unless you get your hands dirty. The book
provides many examples and exercises, and many of the code snippets can be tested in the
REPL.
Your colleagues may be less eager to explore than you. Expect them to protest your adoption of
this new style and to look perplexed at your code and say things like, “why not just do x?”
(where x is boring, obsolete, and usually harmful). Don’t discuss. Just sit back and watch them
eventually turn around and use your techniques to solve issues they run into again and again.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Acknowledgments
I’d like to thank Paul Louth, who not only provided inspiration through his LanguageExt library—
from which I borrowed many good ideas—but who also graciously reviewed the book at various
stages.
Manning’s thorough editorial process ensured that the quality of this book is infinitely better than
if I had been left to my own means. For this, I’d like to thank the team that collaborated on the
book, including Mike Stephens, development editor Marina Michaels, technical editor Joel
Kotarski, technical proofreader Jürgen Hoetzel, and copyeditor Andy Carroll.
Special thanks to Daniel Marbach and Tamir Dresher for their technical insights, as well as to all
those who took part in the peer reviews, including Alex Basile, Aurélien Gounot, Blair Leduc,
Chris Frank, Daniel Marbach, Devon Burriss, Gonzalo Barba López, Guy Smith, Kofi Sarfo,
Pauli Sutelainen, Russell Day, Tate Antrim, and Wayne Mather.
Thanks to Scott Wlaschin for sharing his articles at http://fsharpforfunandprofit.com, and to the
many other members of the FP community who share their knowledge and enthusiasm through
articles, blogs, and open source.
About this Book
This book aims to show how you can leverage functional techniques in C# to write code that is
concise, elegant, robust, and maintainable.
Who should read this book
This book is for an ambitious breed of developer. You know the C# language and the .NET
framework. You have experience developing real-world applications and are familiar with OOP
concepts, patterns, and best practices. Yet, you’re looking to expand your arsenal by learning
functional techniques so that you can make the most out of C# as a multiparadigm language.
If you’re trying or planning to learn a functional language, this book will also be hugely
valuable, because you’ll learn how to think functionally in a language you’re familiar with.
Changing the way you think is the hard part; once that’s achieved, learning the syntax of any
particular language will be relatively easy.
How this book is organized
The book consists of 15 chapters, divided into 3 parts:
Part 1 covers the basic techniques and principles of functional programming. We’ll start by
looking at what functional programming is and how C# supports programming in a
functional style. We’ll then look at the power of higher-order functions, function purity
and its relation to testability, the design of types and function signatures, and how simple
functions can be composed into complex programs. By the end of part 1, you’ll have a
good feel for what a program written in a functional style looks like and for the benefits
that this style has to offer.
With these basic concepts covered, we’ll pick up some speed in part 2 and move on to
wider-reaching concerns, such as functional error handling, modularizing and composing
an application, and the functional approach to understanding state and representing change.
By the end of part 2, you’ll have acquired a set of tools enabling you to effectively tackle
many programming tasks using a functional approach.
Part 3 will tackle more advanced topics, including lazy evaluation, stateful computations,
asynchrony, data streams, and concurrency. Each chapter in part 3 introduces important
techniques that have the potential to completely change the way you write and think about
software.
You’ll find a more detailed breakdown of the topics in each chapter, and a representation of what
chapters are required before reading any particular chapter, on the inside front cover page.
The book aims to stay true to real-world scenarios. To do this, many examples deal with practical
tasks such as reading configuration, connecting to a database, validating HTTP requests, and so
on—things you may already know how to do, but you’ll see them with the fresh perspective of
functional thinking.
Throughout the book, I use a long-running example to illustrate how FP can help when writing
LOB applications. For this, I’ve chosen an online banking application for the fictitious Bank of
Codeland (BOC)—naff, I know, but at least it has the obligatory three-letter acronym. Because
most people have access to an online banking facility, it should be easy to imagine the required
functionality and plain to see how the problems discussed are relevant to real-world applications.
I also use scenarios to illustrate how to solve typical programming problems in a functional style.
The constant back and forth between practical examples and FP concepts will hopefully help
bridge the gap between theory and practice—something I found wanting in the existing
literature, as I mentioned.
A language like C# may have functional features, but to fully leverage these you’ll often use
libraries that facilitate common tasks. Microsoft has provided several libraries that facilitate
programming in a functional style, including these:
System.Linq—Yes, in case you didn’t know, it’s a functional library! I assume you’re
familiar with it, given that it’s such an important part of .NET.
System.Collections.Immutable—This is a library of immutable collections, which we’ll start
using in chapter 9.
System.Reactive—This is an implementation of the Reactive Extensions for .NET, allowing
you to work with data streams, which we’ll discuss in chapter 14.
This still leaves out plenty of other important types and functions that are staples of FP. As a
result, several independent developers have written libraries to fill those gaps. To date, the most
complete of these is LanguageExt, a library written by Paul Louth to improve the C# developer’s
experience when coding functionally.[1]
1
In the book, I don’t use LanguageExt directly; instead, I’ll show you how I developed my own
library of functional utilities, called LaYumba.Functional, even though it largely overlaps with
LanguageExt. This is pedagogically more useful, for several reasons:
Hon. James Hill is president of the above company. Mr. Hill is a man
of high standing and well known in all parts of this country. He has
been a political leader for years, and has held some very important
positions. He was at one time Postmaster of Vicksburg, Miss., the
largest town in the State. Mr. Hill is now, in 1900, in the United
States Land Office at Jackson, Miss. He was appointed to this
position by President McKinley.
Rev. E. W. Lampton, first vice-president of the company, is also a
well-known man. He has been a very active man in the A. M. E.
Church. His home is at Greenville, Miss., where he owns valuable
property. Mr. Lampton has been at the head of the Masonic order for
the State of Mississippi, and thousands of dollars have been
disbursed by him for the benefit of widows and orphans annually.
MR. EUGENE BURKINS.
EUGENE BURKINS,
Inventor of the Burkins Automatic Machine-Gun.
Mr. Geo. E. Jones, of Little Rock, Ark., is beyond doubt one of the
most successful business men among the colored people. He began
life a very poor boy, without friends or capital, and has by hard work
and close economy placed himself among the most prominent
business men of his city. Mr. Jones is engaged in the undertaking
business, and can say what no other colored man engaged in that
line of work in the South can say, and that is—he has about as much
patronage among the white people as he has with his own race. Mr.
Jones first started in business as a merchant on a small amount of
money, and finally worked into the undertaking business. He owns
now in Little Rock quite a large amount of property, and among the
different buildings there he has two large brick blocks, one on Main
street, where he has his undertaking establishment, and one on
West Ninth street, which is rented. In the Ninth street block Mr.
Jones has in one room a fine drug store, which he employs a young
druggist to attend to. He owns a fine lot of horses and carriages
used in his business as an undertaker. His residence is by far the
best furnished home I ever saw owned by a colored man. Mrs.
Jones, his wife, is a very refined and cultured lady.
MR. G. W. HIGGINS.
MR. G. W. HIGGINS.
G. W. Higgins was born in South Carolina, and lived for some time at
Newberry, S. C. He began at an early age to acquire an education in
order that he might be of some help to himself and race. Mr. Higgins
attended Biddle University at Charlotte, N. C., where he took a
course in theology. He was at one time principal of the public school
at Old Fort, N. C., and while teaching there he established a
Presbyterian Church, which is still in existence. After leaving the
Presbyterian work he joined the A. M. E. Zion Connection, and was
appointed pastor at Abington, Va., and afterwards at Johnson City,
Tenn. There he became interested in the industrial advancement of
the colored people, and set about to learn some trade, and secured
work in a first-class steam laundry, and learned the business
thoroughly, and afterwards operated a laundry of his own. Mr.
Higgins came to Cincinnati, O., in 1893 and secured employment
with the Oil and Grease Company of Chas. H. Moore & Co. After five
years of faithful work for that firm he became an expert in the
compounding of the oils and greases made by the firm, and was
offered a larger salary by Burchard & Co., of Cincinnati, who are
refiners of lard oil. For this firm, Mr. Higgins has charge as foreman
of the oil and grease department. He is much thought of by his
employers.
MR. A. MEANS.
A. Means, of Memphis, Tenn., is a practical hatter, and is the only
colored man I know of engaged in that line of work. He has a large
trade and keeps on hand a select assortment of the latest styles in
hats and caps. Mr. Means does a large business in cleaning and
repairing hats.
MR. J. E. HENDERSON.
J. E. Henderson, of Little Rock, Ark., is engaged in the jewelry
business. Mr. Henderson is regarded as a good workman in his line,
and for some years before he began business for himself he did the
repair work for one of the leading jewelry houses of Little Rock. He
gets a great deal of his work now from the white people. I hope
before many years to see a larger number of colored men engaged
in the jewelry trade.
SOUTHERN MERCANTILE COMPANY.
The Southern Mercantile Company, Pine Bluff, Ark., is a company of
excellent business men, who are demonstrating that colored men
can manage a successful business enterprise. They handle a large
stock of dry goods, groceries, boots and shoes and plantation
supplies. They do both a wholesale and retail business. The firm has
in it such men as Wiley Jones, Fred. Havis, who is president of the
company, and Mr. M. R. Perry, as secretary and treasurer. Mr. Perry is
a graduate from one of the best schools in the country and regarded
as a splendid business man.
MR. L. CARTER.
L. Carter, of Greenville, Miss., was born of slave parents at Carthage,
Tenn. He has been in Mississippi since 1866. Mr. Carter owns and
operates the only large book store in the country owned by a
colored man. He keeps a splendid stock of school books, blank
books, stationery, periodicals and a good assortment of story books
and toys. In speaking of where he got the greater part of his
support, he said that at least two-thirds of his patronage came from
the white people, and among the best class of them. Mr. Carter
owns good property in Greenville as a residence, and is regarded as
one of the prominent citizens.
DAVIS & ROBINSON.
Davis & Robinson, of Jacksonville, Fla., are the leading commission
merchants of that city. They do both a wholesale and retail business
in oranges, fruits, strawberries, northern produce, turkeys, chickens,
eggs, early vegetables. They handle melons in car-load lots and keep
all kinds of game in season. They also supply the large hotels there
with all they need in their line. Both of these men are respected and
regarded as excellent business men by the leading people.
MRS. ELLA HENDERSON.
Mrs. Ella Henderson, who is located at Natchez, Miss., has opened a
very excellent millinery store, where she keeps a splendid stock of
goods in that line of trade. As I have stated in other parts of this
book, there are very few colored ladies engaged in the millinery
business. This is to be regretted, for there is an opening for some
one to do well in all towns where the colored population is large.
Mrs. Henderson has taken special training to thoroughly prepare
herself for the successful management of her business. She started
in a small way, and has twice since she opened her store had to
enlarge the room in order to meet the demands of her trade. She
buys her stock from the best houses in the country. The travelling
salesmen who visit the town with millinery goods call on her and
give her the same attention to secure her patronage as they do the
white ladies in the same business. I hope that many colored ladies
who may read this short sketch will be inspired to at least try and
start some kind of business.
RISHER BAKERY COMPANY.
Mr. H. T. Risher, of Jackson, Miss., who owns and operates a very
large and successful bakery business, has taken a new departure in
the line of business for colored people. I have only found two men
engaged in that line of work. One was Mr. Jones, at Danville, Va.,
and Mr. Risher, of Jackson. His place of business is equipped with all
the modern appliances for a first-class bake shop. Mr. Risher's trade
extends to many of the towns in the State, where he supplies
merchants who sell his bread. He has several delivery wagons that
are used to supply his city patrons. Mr. Risher is regarded as a very
excellent man, who is much interested in all that will advance the
cause of his race in a business and educational way. He has been
one of the leading spirits in building up Campbell College at Jackson,
one of the A. M. E. schools. Mr. Risher owns splendid property and
enjoys the respect of both white and colored people.
MR. F. B. COFFIN.
F. B. Coffin, of Little Rock, Ark., is a druggist by profession. He
operates a very fine drug store at Little Rock for Mr. Geo. E. Jones.
Mr. Coffin is a graduate from Meharry Medical College, at Nashville,
Tenn. In addition to his work as a druggist he has written a book of
poems, entitled "Coffin's Poems." The book has 248 pages, and
contains some very interesting matter, which shows his ability as a
writer. Part of his book is devoted to the question of Lynch law, and
he speaks out like a true and brave man against that awful curse to
this country.
MR. J. E. BUSH.
J. E. Bush was born in Moscow, Tenn., in 1856. His parents moved to
Arkansas during the rebellious unpleasantness of 1862. At an early
age he manifested the energy and self-reliance that has developed
him into the useful prominence of a worthy and highly respected
citizen. He earned his tuition at school by moulding brick. He may
have made "bricks without straw," but his manliness has never
allowed him to complain of the many hardships he has endured to
overcome the difficulties in his experience or surmount the obstacles
with which he has so often been brought into contact. Mr. Bush was
educated in the schools of Little Rock, Ark. He has been successful in
life and owns valuable property there. He has also held some
important political positions, and was appointed in 1898 by President
McKinley as Receiver of the United States Land Office at Little Rock.
DR. G. W. BELL.
Dr. G. W. Bell, of Pine Bluff, Ark., is a graduate of Lincoln University,
and he took his medical training at "The University of Michigan." He
has a very large practice. Dr. Bell has established, in connection with
his profession, a private sanitarium for the benefit of those who
come to him from a distance for treatment. He has built a
comfortable building for that purpose, and I think it is the only
institution of the kind carried on by a colored doctor in the State.
MISS MATTIE JENNETE JOHNSON.
Miss Mattie J. Johnson is employed as a saleslady in Siegel, Cooper
& Company's large store in the city of Chicago. She began work for
them in 1893, and has been there ever since. Miss Johnson is in the
grocery department, and is looked upon by her employers as one of
the most competent women in their store. She has many warm
friends among the patrons of the establishment. While Miss Johnson
is the first colored lady thus employed, knowing that she was
colored when they engaged her, I am sure she will not be the last,
and I hope many young women will prepare themselves for some
useful place.
DR. T. M. DORAM, M. D. V.
DR. T. M. DORAM, M. D. V.
MR. H. A. LOVELESS.
Mr. H. A. Loveless is also a resident of Montgomery, Ala., and must
be classed among the successful business men of the race. He, like
Mr. Adams, began business on a small scale, and by hard work and
an untiring effort he has made a showing no man need to be
ashamed of. Mr. Loveless operates a coal and wood yard, where he
gives employment to a large force of men. He also owns teams and
does general hauling, and has nine fine carriages that are kept on
the street for the benefit of the general public. Then, in addition to
what I have referred, Mr. Loveless has a very large undertaker's
establishment, which also gives quite a number of people
employment. He owns fine town property, and is regarded by both
white and colored people as a very excellent man. He takes an
active part in church work, and is especially interested in every
movement that will advance the colored people in the development
of business interest. He along with other leading men of the race
feel that industrial education, and a good business training for the
young, will prove a great factor in the solution of what we call a
"race problem."
PROF. R. B. HUDSON.
PROF. R. B. HUDSON.
Lewis H. Latimer, of New York city, is the only member of the race
engaged in the line of work he represents. In 1880 Mr. Latimer
entered the employ of the United States Electric Lighting Company
as a draftsman and private secretary to Sir Hiram S. Maxim, of
Maxim gun fame. In 1881 Mr. Latimer was sent to England by the
above-named company to establish the manufacture of the
incandescent electric lamps in the factory of the Maxim, Weston
Electric Light Company of London. He returned in the latter part of
1882, and continued only a few months in the employment of the
company who sent him abroad. For some time he served as
draftsman and electrician in several minor companies. He was
employed by the Edison Electric Light Company in 1886, and has
remained with them practically ever since, although that company
has been absorbed by the General Electric Lighting Company. Mr.
Latimer is kept in what is known as the legal expert department, and
is regarded as a very competent man in his profession. He stands
almost alone in his work as a colored man. I have only known of
about three members of the race who have made any effort along
that line, but the other two never succeeded in making any
headway, at least not enough to become known to any extent. Now,
one can easily see that the people who employ Mr. Latimer must
hold him in high esteem and place in him the most implicit
confidence, or they would never have sent him to another country to
represent their business. This mention of Mr. Latimer is another
evidence that colored people are gradually but surely getting into all
lines of business and professions, and I hope that in time we may
call attention to other successful electricians among the race.
MR. J. S. ATWOOD.
MR. J. S. ATWOOD.