Functional Programming in C#: How To Write Better C# Code 1st Edition Enrico Buonanno - Discover The Ebook With All Chapters in Just A Few Seconds
Functional Programming in C#: How To Write Better C# Code 1st Edition Enrico Buonanno - Discover The Ebook With All Chapters in Just A Few Seconds
com
https://textbookfull.com/product/functional-programming-in-
c-how-to-write-better-c-code-1st-edition-enrico-buonanno/
OR CLICK HERE
DOWLOAD EBOOK
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/introduction-to-programming-
with-c-1st-edition-nhce/
textbookfull.com
Modern C++ for Absolute Beginners: A Friendly Introduction
to C++ Programming Language and C++11 to C++20 Standards
1st Edition Slobodan Dmitrovi■
https://textbookfull.com/product/modern-c-for-absolute-beginners-a-
friendly-introduction-to-c-programming-language-
and-c11-to-c20-standards-1st-edition-slobodan-dmitrovic/
textbookfull.com
https://textbookfull.com/product/c-programming-complete-guide-to-
learn-the-basics-of-c-programming-in-7-days-2nd-edition-xavier-s-
martin/
textbookfull.com
https://textbookfull.com/product/101-challenges-in-c-programming-1st-
edition-yashavant-kanetkar/
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: [email protected]
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.
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:
You can execute many of the shorter snippets of code in a REPL, thereby gaining hands-on
practice with immediate feedback. The more extended examples are available for download at
https://github.com/la-yumba/functional-csharp-code, along with the exercises’ setup and
solutions.
Code listings in the book focus on the topic being discussed, and therefore may omit
namespaces, using statements, trivial constructors, or sections of code that appeared in a previous
listing and remain unchanged. If you’d like to see the full, compiling version of a listing, you’ll
find it in the code repository: https://github.com/la-yumba/functional-csharp-code.
Book forum
Purchase of Functional Programming in C# includes free access to a private web forum run by
Manning Publications where you can make comments about the book, ask technical questions,
and receive help from the author and from other users. To access the forum, go to
https://forums.manning.com/forums/functional-programming-in-c-sharp. You can also learn
more about Manning’s forums and the rules of conduct at
https://forums.manning.com/forums/about.
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.
Exploring the Variety of Random
Documents with Different Content
rauhalliseksi, näimme hänen kasvojensa muuttuvan ja odotimme
hänen loppuansa. Hän eli vielä useita tunteja ja kuoli myöhään
iltapäivällä. En tuntenut enää mitään muuta kuin tylsää tuskaa ja
syvää väsymystä, istuin kuumin, kuivin silmin ja nukahdin illalla
kuolinvuoteen ääressä istuessani.
6.
Ensi aluksi oli minulla yllin kyllin tekemistä, joka pidätti minua
mietiskelystä ja epätoivosta. Selvitettäväksi oli jäänyt talo ja laaja
liike saatavineen ja velkoineen, selvitettävinä olivat kirjat ja laskut,
rahaa oli saatu ja lainattu, ja nyt oli kysymys, mitä tästä kaikesta
tulisi. Olin tietysti alusta alkaen päättänyt myydä kaiken, mutta se ei
käynyt niin nopeasti; myöskin äiti oli vielä kiinni vanhassa kodissa ja
isän testamentti oli toimeenpantava, mikä tuotti kaikenlaisia mutkia
ja vaikeuksia. Kirjanpitäjän ja notarin täytyi auttaa, päivät ja viikot
kuluivat neuvotteluihin, rahaa ja velkoja koskevaan kirjeenvaihtoon,
suunnitelmiin ja pettymyksiin. Pian en enää tiennyt, miten selviytyä
näistä laskuista ja virallisista muodollisuuksista, annoin notarin
avuksi vielä asianajajan ja jätin heidän huostaansa koko
sekamelskan.
"Hän voi hyvin. Tiedätte, ettei tämä avioliitto ole ollut minulle
oikein mieleen. Olisin jo kauan sitten mielelläni kerran kysynyt teiltä
yhtä ja toista herra Muothista. Mikäli häntä tunnen, ei minulla ole
valittamisen syytä. Mutta olen kuullut hänestä niin monenlaista:
hänhän kuuluu olleen paljon tekemisissä naisten kanssa. Voitteko
sanoa tästä asiasta mitään?"
"Tiedän sen."
"Hm…"
"Jätä Lotte! Se oli hänelle oikein. Iskuja ei saa kukaan nainen, joka
ei tahdo saada niitä."
"No niin. Siis oopperaani. En vielä lainkaan ole selvillä, minne sitä
ensin tarjoaisin. Sen pitäisi olla hyvä näyttämö, mutta tokko sellainen
huolii teoksestani?"
"Muistan kyllä", sanoin minä, "eikä sinun olisi tarvinnut minua siitä
muistuttaa. Lähtisit ennemmin!"
"En, ystäväni. Siis muistat vielä. No, jos jo silloin rakastit tyttöä,
mikset sanonut siitä sanaakaan minulle? Mikset sanonut: Jätä hänet
rauhaan, jätä hänet minulle! Se olisi ollut kylliksi, olisin ymmärtänyt
viittauksenkin."
"Luonnollisesti, tuomiokirkossa."
7.
Oli pidetty huoli siitäkin, etten saanut kauan ajatella ystävieni häitä
ja sitä tietä saada aihetta mietiskelyihini ja itseni kiduttamiseen.
Äitiäni olin tänä aikana vähän ajatellut. Olin tosin hänen viime
kirjeestään saanut tietää, ettei kotoisen elämän ja rauhan laita ollut
loistavasti, mutta minulla ei ollut enemmän syytä kuin haluakaan
sekaantua molempien naisten väliseen riitaan, vaan totesin sen
jonkunlaista vahingoniloa tuntien asiana, johon nähden minun
ratkaiseva sanani ei ollut tarpeen. Olin sittemmin kirjottanut
saamatta vastausta ja minulla oli oopperani jäljennöksen
tarkastamisessa siksi paljo työtä, ettei minulta riittänyt aikaa ajatella
neiti Schniebeliä.
"Olisi kenties hyvä, että tulisit itse. Lucie tietää nimittäin jo, mitä
ajattelen ja suunnittelen, hän vainuaa sen varsin hyvin; mutta
suhteemme on liiaksi jännittynyt, jotta voisin sanoa hänelle sen,
mikä on tarpeen, oikeassa muodossa. Minun viittailujani siihen
suuntaan, että mieluummin jälleen asuisin yksin kotona ja että tulen
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com