100% found this document useful (1 vote)
9 views

Introducing Functional Programming Using C Leveraging a New Perspective for OOP Developers 1st Edition Vaskaran Sarcar instant download

The document introduces 'Functional Programming Using C#' by Vaskaran Sarcar, aimed at OOP developers seeking to enhance their programming skills. It covers key concepts of functional programming, including immutability, higher-order functions, and function composition, while providing practical examples and exercises. The book is structured into two parts: familiarization with functional programming and harnessing its power in C#.

Uploaded by

einareafiat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
9 views

Introducing Functional Programming Using C Leveraging a New Perspective for OOP Developers 1st Edition Vaskaran Sarcar instant download

The document introduces 'Functional Programming Using C#' by Vaskaran Sarcar, aimed at OOP developers seeking to enhance their programming skills. It covers key concepts of functional programming, including immutability, higher-order functions, and function composition, while providing practical examples and exercises. The book is structured into two parts: familiarization with functional programming and harnessing its power in C#.

Uploaded by

einareafiat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Introducing Functional Programming Using C

Leveraging a New Perspective for OOP Developers


1st Edition Vaskaran Sarcar pdf download

https://ebookname.com/product/introducing-functional-programming-
using-c-leveraging-a-new-perspective-for-oop-developers-1st-
edition-vaskaran-sarcar/

Get Instant Ebook Downloads – Browse at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Functional JavaScript Introducing Functional


Programming with Underscore js 1st Edition Michael
Fogus

https://ebookname.com/product/functional-javascript-introducing-
functional-programming-with-underscore-js-1st-edition-michael-
fogus/

Introducing Windows 7 for Developers 1st Edition Yochay


Kiriaty

https://ebookname.com/product/introducing-windows-7-for-
developers-1st-edition-yochay-kiriaty/

Introducing Microsoft Visual Basic 2005 for developers


Sean Campbell

https://ebookname.com/product/introducing-microsoft-visual-
basic-2005-for-developers-sean-campbell/

Paradise Lost State Failure in Nepal 1st Edition Subho


Basu

https://ebookname.com/product/paradise-lost-state-failure-in-
nepal-1st-edition-subho-basu/
Understanding Art 10th Edition Lois Fichner-Rathus

https://ebookname.com/product/understanding-art-10th-edition-
lois-fichner-rathus/

High Throughput Screening in Chemical Catalysis


Technologies Strategies and Applications 1st Edition
Alfred Hagemeyer

https://ebookname.com/product/high-throughput-screening-in-
chemical-catalysis-technologies-strategies-and-applications-1st-
edition-alfred-hagemeyer/

Vascular Medicine A Companion to Braunwald s Heart


Disease Expert Consult Online and Print 1e 1st Edition
Mark A. Creager

https://ebookname.com/product/vascular-medicine-a-companion-to-
braunwald-s-heart-disease-expert-consult-online-and-print-1e-1st-
edition-mark-a-creager/

Meningiomas Expert Consult Online and Print Expert


Consult Title Online Print 1 Har/Psc Edition M.
Necmettin Pamir

https://ebookname.com/product/meningiomas-expert-consult-online-
and-print-expert-consult-title-online-print-1-har-psc-edition-m-
necmettin-pamir/

This Bright Light of Ours Stories from the Voting


Rights Fight 1st Edition Maria Gitin

https://ebookname.com/product/this-bright-light-of-ours-stories-
from-the-voting-rights-fight-1st-edition-maria-gitin/
Mechanics of Materials SI Edition James M. Gere

https://ebookname.com/product/mechanics-of-materials-si-edition-
james-m-gere/
Introducing
Functional
Programming
Using C#
Leveraging a New Perspective for
OOP Developers

Vaskaran Sarcar
Introducing Functional Programming Using C#: Leveraging a New Perspective for
OOP Developers
Vaskaran Sarcar
Kolkata, West Bengal, India

ISBN-13 (pbk): 978-1-4842-9696-7 ISBN-13 (electronic): 978-1-4842-9697-4


https://doi.org/10.1007/978-1-4842-9697-4

Copyright © 2023 by Vaskaran Sarcar


This work is subject to copyright. All rights are reserved 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.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Smriti Srivastava
Development Editor: Laura Berendson
Editorial Project Manager: Mark Powers
Cover designed by eStudioCalamar
Cover image by BoliviaInteligente on Unsplash (www.unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.
springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science
+ Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint, paperback,
or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at www.apress.com/bulk-sales.
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.
Paper in this product is recyclable
This book is dedicated to all those developers who want to
improve their applications and do not give up easily.
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewers����������������������������������������������������������������������������� xiii


Acknowledgments���������������������������������������������������������������������������������������������������xv

Introduction�����������������������������������������������������������������������������������������������������������xvii

Part I: Getting Familiar with Functional Programming����������������������������������� 1


Chapter 1: Functional Programming Overview��������������������������������������������������������� 3
C# Supports Multiple Paradigms�������������������������������������������������������������������������������������������������� 3
Functions and Methods Are Equivalent in C#�������������������������������������������������������������������������� 4
Important Characteristics of FP���������������������������������������������������������������������������������������������������� 5
FP Treats Functions as First-Class Citizens����������������������������������������������������������������������������� 6
FP Prefers Immutability����������������������������������������������������������������������������������������������������������� 8
FP Prefers Pure Functions����������������������������������������������������������������������������������������������������� 11
FP Follows a Declarative Style���������������������������������������������������������������������������������������������� 18
FP vs. OOP����������������������������������������������������������������������������������������������������������������������������������� 24
FP Benefits���������������������������������������������������������������������������������������������������������������������������������� 25
Exercises������������������������������������������������������������������������������������������������������������������������������������� 26
Summary������������������������������������������������������������������������������������������������������������������������������������ 28
Solutions to Exercises����������������������������������������������������������������������������������������������������������������� 28

v
Table of Contents

Chapter 2: Understanding Functions���������������������������������������������������������������������� 33


Mathematical Background of Functions������������������������������������������������������������������������������������� 33
Mathematical Functions vs. C# Functions���������������������������������������������������������������������������������� 35
Representing Functions in C#����������������������������������������������������������������������������������������������������� 35
Using Static Methods������������������������������������������������������������������������������������������������������������ 35
Using Delegates and Lambdas���������������������������������������������������������������������������������������������� 39
Using a Dictionary����������������������������������������������������������������������������������������������������������������� 42
Built-in Delegates Are Important������������������������������������������������������������������������������������������������� 45
Higher-Order Function����������������������������������������������������������������������������������������������������������������� 46
Custom HOF��������������������������������������������������������������������������������������������������������������������������� 46
Built-in HOF��������������������������������������������������������������������������������������������������������������������������� 48
First-Order Function�������������������������������������������������������������������������������������������������������������������� 49
Refactoring Impure Functions����������������������������������������������������������������������������������������������������� 49
Program with Impurities�������������������������������������������������������������������������������������������������������� 50
Removing Impurities�������������������������������������������������������������������������������������������������������������� 51
Exercises������������������������������������������������������������������������������������������������������������������������������������� 53
Summary������������������������������������������������������������������������������������������������������������������������������������ 54
Solutions to Exercises����������������������������������������������������������������������������������������������������������������� 55

Chapter 3: Understanding Immutability����������������������������������������������������������������� 59


What Is Immutability?����������������������������������������������������������������������������������������������������������������� 59
Immutable Objects in .NET���������������������������������������������������������������������������������������������������� 59
Reviewing Mutable Types����������������������������������������������������������������������������������������������������������� 61
Programming with a Mutable Type���������������������������������������������������������������������������������������� 61
The Path Toward Immutability����������������������������������������������������������������������������������������������������� 62
Achieving External Immutability�������������������������������������������������������������������������������������������� 62
Enforcing Internal Immutability��������������������������������������������������������������������������������������������� 65
Better Code Using Modern Features�������������������������������������������������������������������������������������� 68
More on Immutability������������������������������������������������������������������������������������������������������������������ 72
Understanding Shallow Immutability������������������������������������������������������������������������������������� 73
Searching for a Solution�������������������������������������������������������������������������������������������������������� 77

vi
Table of Contents

Making a Better Solution������������������������������������������������������������������������������������������������������� 80


Implementing Popsicle Immutability������������������������������������������������������������������������������������� 83
Exercises������������������������������������������������������������������������������������������������������������������������������������� 87
Summary������������������������������������������������������������������������������������������������������������������������������������ 88
Solutions to Exercises����������������������������������������������������������������������������������������������������������������� 89

Part II: Harnessing the Power of Functional Programming�������������������������� 93


Chapter 4: Composing Functions Using Pipelining������������������������������������������������� 95
Overview������������������������������������������������������������������������������������������������������������������������������������� 95
Coding Functional Composition��������������������������������������������������������������������������������������������� 95
Importance of Chaining Functions���������������������������������������������������������������������������������������������� 99
Program Without Chaining Functions������������������������������������������������������������������������������������ 99
Refactoring Using Chaining Functions�������������������������������������������������������������������������������� 102
Applying Composition��������������������������������������������������������������������������������������������������������������� 106
Using Pipelining������������������������������������������������������������������������������������������������������������������� 106
Using HOFs�������������������������������������������������������������������������������������������������������������������������� 109
Exercises����������������������������������������������������������������������������������������������������������������������������������� 112
Summary���������������������������������������������������������������������������������������������������������������������������������� 113
Solutions to Exercises��������������������������������������������������������������������������������������������������������������� 113

Chapter 5: Composing Functions Using Currying������������������������������������������������� 119


Overview of Currying���������������������������������������������������������������������������������������������������������������� 119
Program Without Currying��������������������������������������������������������������������������������������������������� 120
Using the Concept of Currying��������������������������������������������������������������������������������������������� 121
Using External NuGet Packages������������������������������������������������������������������������������������������������ 129
Using Curryfy����������������������������������������������������������������������������������������������������������������������� 130
Exercises����������������������������������������������������������������������������������������������������������������������������������� 136
Summary���������������������������������������������������������������������������������������������������������������������������������� 138
Solutions to Exercises��������������������������������������������������������������������������������������������������������������� 139

vii
Table of Contents

Chapter 6: Handling Temporal Coupling��������������������������������������������������������������� 145


Temporal Coupling Overview���������������������������������������������������������������������������������������������������� 146
How Does This Happen?������������������������������������������������������������������������������������������������������ 146
Recognizing the Problem���������������������������������������������������������������������������������������������������������� 146
A Program That Suffers from Temporal Coupling���������������������������������������������������������������� 147
Removing the Effect������������������������������������������������������������������������������������������������������������������ 155
A Better Program����������������������������������������������������������������������������������������������������������������� 156
Exercises����������������������������������������������������������������������������������������������������������������������������������� 165
Summary���������������������������������������������������������������������������������������������������������������������������������� 167
Solutions to Exercises��������������������������������������������������������������������������������������������������������������� 167

Chapter 7: Functional Patterns����������������������������������������������������������������������������� 171


Map Pattern������������������������������������������������������������������������������������������������������������������������������ 172
Understanding the Problem������������������������������������������������������������������������������������������������� 173
Initial Solution���������������������������������������������������������������������������������������������������������������������� 173
Better Solution��������������������������������������������������������������������������������������������������������������������� 177
Concise Solution������������������������������������������������������������������������������������������������������������������ 178
Select As Map���������������������������������������������������������������������������������������������������������������������� 182
Introducing Functors����������������������������������������������������������������������������������������������������������� 186
Conclusion��������������������������������������������������������������������������������������������������������������������������� 186
Bind Pattern������������������������������������������������������������������������������������������������������������������������������ 187
Understanding the Problem������������������������������������������������������������������������������������������������� 187
Initial Solution���������������������������������������������������������������������������������������������������������������������� 188
FP-Based Solution��������������������������������������������������������������������������������������������������������������� 189
SelectMany As Bind������������������������������������������������������������������������������������������������������������� 191
What About Monads?����������������������������������������������������������������������������������������������������������� 192
Conclusion��������������������������������������������������������������������������������������������������������������������������� 193
Filter Pattern����������������������������������������������������������������������������������������������������������������������������� 194
Understanding the Problem������������������������������������������������������������������������������������������������� 194
Initial Solution���������������������������������������������������������������������������������������������������������������������� 195
Where As Filter�������������������������������������������������������������������������������������������������������������������� 198

viii
Table of Contents

Fold Pattern������������������������������������������������������������������������������������������������������������������������������ 199


Understanding the Problem������������������������������������������������������������������������������������������������� 202
Solutions Using Built-in Functions�������������������������������������������������������������������������������������� 202
Conclusion��������������������������������������������������������������������������������������������������������������������������� 205
Revisiting ForEach�������������������������������������������������������������������������������������������������������������������� 207
Exercises����������������������������������������������������������������������������������������������������������������������������������� 208
Summary���������������������������������������������������������������������������������������������������������������������������������� 210
Solutions to Exercises��������������������������������������������������������������������������������������������������������������� 210

Chapter 8: Exception Handling����������������������������������������������������������������������������� 215


Reviewing Exception Handling in OOP�������������������������������������������������������������������������������������� 215
Imperative Style of Programming���������������������������������������������������������������������������������������� 217
Exception Handling in FP���������������������������������������������������������������������������������������������������������� 218
Using language-ext������������������������������������������������������������������������������������������������������������� 219
Introducing the Either Type�������������������������������������������������������������������������������������������������� 219
Handling a Single Exception������������������������������������������������������������������������������������������������ 224
Handling Multiple Exceptions���������������������������������������������������������������������������������������������� 226
Chaining Exceptions������������������������������������������������������������������������������������������������������������ 230
Handling Null Values����������������������������������������������������������������������������������������������������������������� 238
Introducing the Option Type������������������������������������������������������������������������������������������������� 239
Exercises����������������������������������������������������������������������������������������������������������������������������������� 248
Summary���������������������������������������������������������������������������������������������������������������������������������� 251
Solutions to Exercises��������������������������������������������������������������������������������������������������������������� 252

Chapter 9: Miscellaneous Topics�������������������������������������������������������������������������� 257


Helpful Features for FP������������������������������������������������������������������������������������������������������������� 257
Delegates and Lambdas������������������������������������������������������������������������������������������������������ 257
Anonymous Methods����������������������������������������������������������������������������������������������������������� 258
Extension Methods and LINQ����������������������������������������������������������������������������������������������� 259
Type Inference��������������������������������������������������������������������������������������������������������������������� 263
Importing Static Members��������������������������������������������������������������������������������������������������� 263

ix
Table of Contents

Immutability Features���������������������������������������������������������������������������������������������������������� 264


Expression-Bodied Members���������������������������������������������������������������������������������������������� 265
Local Functions������������������������������������������������������������������������������������������������������������������� 268
Tuples���������������������������������������������������������������������������������������������������������������������������������� 270
Pattern Matching����������������������������������������������������������������������������������������������������������������� 272
Revisiting Option<T>���������������������������������������������������������������������������������������������������������������� 275
Bind Function���������������������������������������������������������������������������������������������������������������������� 277
Return Function������������������������������������������������������������������������������������������������������������������� 279
Introducing Monads������������������������������������������������������������������������������������������������������������������ 280
Definition����������������������������������������������������������������������������������������������������������������������������� 280
Mathematical Background�������������������������������������������������������������������������������������������������� 281
Monad Laws������������������������������������������������������������������������������������������������������������������������ 281
Chaining Multi-argument Functions����������������������������������������������������������������������������������������� 283
Final Suggestions���������������������������������������������������������������������������������������������������������������������� 285
Command Query Separation������������������������������������������������������������������������������������������������ 285
Learn Design Patterns and Anti-Patterns���������������������������������������������������������������������������� 285
Don’t Let Failures Stop You�������������������������������������������������������������������������������������������������� 286
How Much Functional Code Do I Need?������������������������������������������������������������������������������ 287
Applications of FP��������������������������������������������������������������������������������������������������������������������� 287
The Road Ahead������������������������������������������������������������������������������������������������������������������������ 287
Exercises����������������������������������������������������������������������������������������������������������������������������������� 288
Summary���������������������������������������������������������������������������������������������������������������������������������� 290
Solutions to Exercises��������������������������������������������������������������������������������������������������������������� 291

Appendix: Recommended Resources������������������������������������������������������������������� 295

Index��������������������������������������������������������������������������������������������������������������������� 297

x
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.

xi
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/.

Shekhar Kumar Maravi is a lead engineer in design and


development, whose main interests are programming
languages, algorithms, and data structures. He obtained his
master’s degree in computer science and engineering from
the Indian Institute of Technology, Bombay (India). After
graduation, he joined Hewlett-­Packard’s R&D Hub in India
to work on printer firmware. Currently he is a technical lead
engineer for automated pathology lab diagnostic devices in
the Siemens Healthcare R&D division. He can be reached
by email at [email protected] or via LinkedIn at
https://www.linkedin.com/in/shekharmaravi.

xiii
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.

xv
Introduction
Throughout the ages, prophets have suggested that most of us are not reaching our full
potential. If you look at the great achievers in any field in the current world, you will find
that they are hard workers, and they strive to keep improving. They put in extra effort to
improve their skills, and in many cases, they even hire coaches to learn new techniques.
Then, one day, they discover that all their hard work starts to pay off: they become
masters in their chosen field.
The following quote from the Chinese philosopher Confucius perfectly
summarizes this:

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.

Now let’s apply this philosophy to programming. As a developer, are you reaching
your full potential with C#? I may not know your reply, but I certainly know my answer.
Even after working with C# for more than 14 years, there is still more to learn.
One evening I asked myself, how could I improve my C# skills? I could continue
to try to learn new features and practice them, but intuitively, I knew there was an
alternative answer. So, I started searching for tips and eventually discovered that most of
the time I was using C# for object-oriented programming (OOP). Indeed, it is a perfect
fit for OOP, and there is nothing wrong with this tendency. But what about functional
programming (FP) using C#? It’s not that I never used it (in fact, C# developers are very
much familiar with LINQ), but I was not very conscious of it. So, I keep browsing through
various resources, such as books, articles, and online courses. Eventually, I discovered
that during its development, C# started embracing functional features too, and as a
result, it has become a powerful hybrid language.
I became very interested in the topic and tried to learn more about it. From this
time onward, I started facing challenges. There were some good resources, but I could
not stitch them together to serve my needs. This is why I started documenting my notes
when I was experimenting with using C# in a functional way. This book is a result of
those efforts.

xvii
Introduction

So, welcome to your journey through Introducing Functional Programming Using C#:
Leveraging a New Perspective for OOP Developers.
C# is a powerful programming language, is well accepted in the programming world,
and helps you make a wide range of applications. These are the primary reasons it is
continuously growing in popularity and is always in high demand. So, it is not a surprise
that existing and upcoming developers (for example, college students and programming
lovers) are curious to learn C# and want to create their applications using it.
Many developers try to learn it in the shortest possible time frame and then claim
they know C# well. In fact, many resources claim you can unlock the real power of C# in
a day, a week, or a month. But is this true? I think not. Remember, I’m 14 years in and I’m
still learning.
Malcolm Gladwell’s 10,000-hour rule says that the key to achieving world-class
expertise in any skill is, to a large extent, a matter of practicing the correct way, for a total
of around 10,000 hours. So, even though we may claim that we know something very
well, we actually know very little. Learning is a continuous process, with no end to it.
Then should we stop learning? Definitely, the answer is no. There is something called-
effective learning. It teaches you how to learn fast to serve your need. This is the context
where I like to remind you about the Pareto principle or 80-20 rule. This rule simply states
that 80% of outcomes come from 20% of all causes. This is useful in programming too.
When you truly learn the fundamental aspects of FP, you can use it effectively to improve
your code. Most importantly, your confidence level will raise to a level from where you
can learn more easily. This book is for those who acknowledge this fact. It helps you to
understand the core principles of FP with plenty of Q&A sessions and exercises.

How Is This Book Organized?


The book has two major parts, which are as follows:

• Part I consists of the first three chapters, which start with an overview
of functional programming (FP). Then we’ll discuss functions and
immutability in depth. These are the building blocks for FP and what
you need to understand to move on to Part II of this book.
• C# is a multiparadigm language, and Part II reveals its potential.
This part will cover how to harness the power of FP. In addition,
two well-known external libraries, called Curryfy and language-ext,

xviii
Introduction

are discussed in this part. The first one is used in Chapter 5 when I
discuss currying. The second one is used in Chapter 8 and Chapter 9
when I discuss functional error handling and the Monad pattern.

The best way to learn something is by analyzing case studies, asking questions
about any doubts you have, and doing exercises. So, throughout this book, you will see
interesting code snippets, “Q&A Sessions,” and exercises. Each question in the “Q&A
Sessions” sections is marked with <chapter_no>.<Question_no>. For example, 5.3 means
question 3 from Chapter 5. You can use the simple exercises to evaluate your progress.
Each question in these exercises is marked with E<chapter_no>.<Question_no>. For
example, E6.2 means exercise 2 from Chapter 6.
The code examples and questions and answers (Q&As) are straightforward. I believe
that by analyzing these Q&As and doing the exercises, you can verify your progress.
They are presented to make your future learning easier and more enjoyable, but most
importantly, they will help you become confident as a developer.
You can download all the source code of the book from the publisher’s website,
where you can also find an errata list for the book. I suggest that you visit that website to
receive any important corrections or updates.

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.

xix
Introduction

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.

xx
Introduction

• 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.

Guidelines for Using This Book


Here are some suggestions so you can use the book more effectively:

• This book suits you best if you are familiar with some advanced
features in C# such as delegates and lambda expressions. If not,
please read about these topics before you start reading this book.

• I organized the chapters in an order that can help grow your


functional thinking with each chapter. Therefore, I recommend
reading the chapters sequentially.

• The code in this book should give you the expected output in future
versions of C#/Visual Studio as well. Though I believe that the results
should not vary in other environments, you know the nature of
software: it is naughty. So, I recommend that if you want to see the
exact same output as in the book, you mimic the same environment.

• You can download and install the Visual Studio IDE from https://
visualstudio.microsoft.com/downloads/ (see Figure I-1).

xxi
Introduction

Figure I-1. Download link for Visual Studio 2022, Visual Studio for Mac, and
Visual Studio Code

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.

Conventions Used in This Book


In many places, I point you to Microsoft’s documentation. Why? As the creator of C#,
Microsoft is the primary authority on each feature.

xxii
Introduction

I’ve used top-level statements heavily in this book. Consequently, there is no need
for me to explicitly write the Main method for console applications. You understand that
using this technique, I minimized the code lengths. When you use top-level statements,
the C# compiler does the necessary job on your behalf in the background. Top-level
statements have been supported since C# 9.0.
I also like to add that I enabled implicit usings for my C# projects. The implicit
usings feature automatically adds common global using directives for the type of
project you are building. Starting from C#10.0, this feature is also supported. Otherwise,
I had to add the necessary directives to my programs manually.
Finally, all the output/code in the book uses the same font and structure. To draw
your attention in some places, I have used bold fonts. For example, consider the
following output fragment (taken from Chapter 3 where I discuss external immutability):

Understanding Mutability and Immutability.


Name: Sam, ID:1
The emp1's hashcode:43942917
The temp's hashcode:43942917
Name: Sam, ID:2
The emp1's hashcode:59941933
The temp's hashcode:43942917

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.

xxiii
PART I

Getting Familiar with


Functional Programming
Part I consists of three chapters. It starts with an overview of functional programming
(FP). Then it discusses functions and immutability in depth. Specifically, Part I covers
the following topics:
• Chapter 1 provides a quick overview of functional programming and
describes the important characteristics of FP. This chapter compares
FP and object-oriented programming (OOP) and also points out the
key benefits of using FP.
• Functions are the building blocks for FP. Chapter 2 provides a
detailed discussion of functions and covers first-order and higher-­
order functions. This chapter also shows a simple technique for
refactoring impure functions into pure functions and making your
code more “functional.”
• Immutability is another important characteristic of FP. Chapter 3
discusses this topic in depth with examples of external, internal,
shallow, and popsicle immutability using features available in C#.

In brief, these are the building blocks for FP and the foundations you’ll need to
understand before reading Part II of this book.
CHAPTER 1

Functional Programming
Overview
You can reach a destination using different vehicles. If the destination is well connected
to transportation routes, you can use a car, a bus, a train, or an airplane. If the destination
is nearby, you may opt for a bicycle. If you are health conscious, you may prefer to walk.
This is simple to understand. Now think about some special scenarios: you need to
reach your destination as soon as possible, but it is not a nearby location. Are you going
to walk? The answer is no. In a situation like this, you will want to use a vehicle to reach
your destination faster. But when you are not in a hurry or want to avoid a crowded bus,
you may prefer to walk. Depending on the context, one approach might be a better fit
compared to others.
The programming world is no different. You can use different programming styles
to create the same application. Each approach has its pros and cons. Based on the given
constraints in an application, you might prefer one approach over another. If you are
aware of multiple routes, you can choose the approach that suits your needs best.

C# Supports Multiple Paradigms


Different programming languages usually target different coding styles/paradigms.
But when programming language developers introduce new features to make a language
richer, the features may not follow the original programming style; instead, languages
can support multiple programming paradigms. As a result, over time these computer
languages become hybrid in nature. The associated benefit is obvious: you can make
an application by choosing the approach that suits your needs best (or even mixing the
approaches). For example, an object-oriented programming (OOP) developer may use
the functional style of coding in some code segments to reap some particular benefit.

3
© Vaskaran Sarcar 2023
V. Sarcar, Introducing Functional Programming Using C#, https://doi.org/10.1007/978-1-4842-9697-4_1
Chapter 1 Functional Programming Overview

C# and F# are .NET programming languages. F# is primarily a functional language,


but it supports the .NET object model. On the other hand, C# is primarily object-
oriented, but it supports several functional features. Particularly, in the latest versions,
you’ll see plenty of support for functional programming. Let’s see what Microsoft
says about this (see https://learn.microsoft.com/en-us/dotnet/standard/linq/
concepts-terminology-functional-transformation):

Historically, general-purpose functional programming languages, such


as ML, Scheme, Haskell, and F#, have been primarily of interest to the
academic community. Although it has always been possible to write pure
functional transformations in C# and Visual Basic, the difficulty of doing so
has not made it an attractive option to most programmers. In recent
versions of these languages, however, new language constructs such as
lambda expressions and type inference make functional programming
much easier and more productive.

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.

Functions and Methods Are Equivalent in C#


Like any other OOP developer, you may like using the term method instead of
function. In C#, you typically place methods inside a class because they do not exist
independently. Since C# primarily supports OOP, you see this kind of design often.
It should not be a surprise to you that functions are the building blocks for FP.
The online link https://learn.microsoft.com/en-us/dotnet/standard/linq/
refactor-pure-functions says the following:

However, in C#, functions are called methods.

Now it is clear that conceptually a method and a function are the same. You see this
terminology difference because these two different paradigms treat functions differently.
In this book, we are exploring functional programming. So, I’ll be using the term function
instead of method in the corresponding places.
In Chapter 2, you’ll see that in addition to the traditional methods, there are other
ways to represent functions.
4
Chapter 1 Functional Programming Overview

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.

5
Chapter 1 Functional Programming Overview

FP Treats Functions as First-Class Citizens


FP treats functions as first-class citizens. What does this mean? This means you can use
them like any other type. For example, you can assign a function to a variable, pass it as
an argument to another function, or use it as a return type. It is possible to store them
in data structures too. When someone says that a programming language supports
first-class functions, you can assume that the programming language supports these
concepts. So, you can think of first-class functions as a programming language feature.
Since we are trying to adopt functional programming, the following questions may
come to your mind:

• What is a function type in C#?

• Does C# have first-class functions?

In C#, delegate types can represent functions. If you are familiar with Func (or
Action) delegates or if you are a lambda lover, probably you know this answer, and you
are already familiar with the usage.
To clarify, let’s consider the Func<int,int> type. You know that this is a delegate type
and it encapsulates a function that accepts one int parameter and returns a value of type
int. Let’s consider a sample line of code that is as follows:

Func<int, int> doubleMaker = x => x * 2;

This code says the following:

• I have a function that takes an integer, multiplies it with 2, and


returns the result.

• I have assigned this function to the variable doubleMaker.

Since the function is assigned to the variable doubleMaker, a developer can write
something like int result = doubleMaker(5);.
You can also pass this function to another function. Demonstration 1 shows such
a usage.

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.

6
Chapter 1 Functional Programming Overview

Note I remind you that I have heavily used top-level statements and enabled
implicit usings for the C# projects in this book. These features came in C#
9.0 and C#10.0 respectively.

using static System.Console;

int temp = 5;
Func<int, int> doubleMaker = x => x * 2;
int result = Container.GetResult(doubleMaker,temp);
WriteLine(result);

static class Container


{
    public static int GetResult(Func<int,int> f, int x)
    {
        return f(x);
    }
}

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.

7
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Gorillas &
Chimpanzees
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.

Title: Gorillas & Chimpanzees

Author: R. L. Garner

Release date: November 16, 2013 [eBook #44191]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Sharon Joiner, Charlie Howard, and the Online


Distributed Proofreading Team at http://www.pgdp.net
(This
file was produced from images generously made available
by The Internet Archive/American Libraries.)

*** START OF THE PROJECT GUTENBERG EBOOK GORILLAS &


CHIMPANZEES ***
Transcriber added tile, author's name, and publishing
information to some versions of the original cover, which
is shown below. All modifications have been placed in the
Public Domain.
Gorillas & Chimpanzees
R. L. Garner.
Gorillas & Chimpanzees

By
R. L. Garner

Illustrated

London
Osgood, McIlvaine & Co.
45 Albemarle Street, W.
1896

To
MY FAITHFUL AND GENEROUS FRIEND
MR. ADOLPH STROHM
WHO HAS GIVEN ME
LIBERAL AID AND UNSWERVING ENCOURAGEMENT
AND TO MY KIND AND STEADFAST FRIEND
MR. JAMES A. DEEMIN
WITH WHOM I SHARED SOME OF THE HARDSHIPS OF TRAVEL
AND A FEW OF THE JOYS OF THE HUNT
THIS VOLUME IS
GRATEFULLY DEDICATED BY
ITS AUTHOR
PREFACE
The present work is the natural product of some years devoted
to a study of the speech and habits of monkeys. It has led up to the
special study of the great apes. The matter contained herein is
chiefly a record of the facts tabulated during recent years in that
field of research.
The aim in view is to convey to the casual reader a more correct
idea than now prevails concerning the physical, mental, and social
habits of these apes.
The favourable conditions under which the writer has been
placed, in the study of these animals in the freedom of their native
jungle, have not hitherto been enjoyed by any other student of
Nature.
A careful aim to avoid all technical terms and scientific
phraseology has been adhered to, and the subject treated in a
simple style. Tedious details are relieved by an ample supply of
anecdotes taken from the writer's own observations, and most of
them are the acts of his own pets or of apes in a wild state. The
author has refrained from rash deductions and abstruse theories, but
has sought to place the animals here treated in their true light,
believing that to dignify the apes is not to degrade man, but to exalt
him even more.
It is hoped that a more perfect knowledge of these animals may
bring man into closer fellowship and deeper sympathy with Nature,
and cause him to realise that all creatures think and feel in some
degree, however small.
THE AUTHOR.
CONTENTS
CHAP. PAGE
PREFACE vii
I MAN AND APE COMPARED 1
II CAGED IN AN AFRICAN JUNGLE 14
III DAILY LIFE AND SCENES IN THE JUNGLE 22
IV THE CHIMPANZEE 36
V PHYSICAL, SOCIAL, AND MENTAL
QUALITIES 46
VI THE SPEECH OF CHIMPANZEES 66
VII THE CAPTURE AND CHARACTER OF
MOSES 76
VIII THE LIFE AND DEATH OF MOSES 92
IX AARON 102
X AARON AND ELISHEBA 116
XI THE DEATH OF AARON AND ELISHEBA 136
XII OTHER CHIMPANZEES 144
XIII OTHER KULU-KAMBAS 176
XIV GORILLAS 188
XV HABITS OF THE GORILLA 213
XVI OTHELLO AND OTHER GORILLAS 234
XVII OTHER APES 252
XVIII THE TREATMENT OF APES IN CAPTIVITY 262
LIST OF ILLUSTRATIONS
Page
Portrait of R. L. Garner Frontispiece
Waiting and Watching in
To face
the Cage 16
Starting for a Stroll " 22
Preparing for the Night " 30
In the Jungle " 42
A Stroll in the Jungle " 54
The Edge of the Jungle " 62
Trading Station in the
"
Interior 102
Plain and Edge of the
"
Forest 108
A Native Canoe " 118
Aaron and Elisheba " 132
Native Village at Moile​—​
"
Interior of Nyanza 146
Consul II. Riding a Tricycle " 164
Consul II. In Full Dress " 170
Native Village at Glass
"
Gaboon 180
Natives Skinning a Gorilla " 191
Skulls of Gorillas​—​Front
and Side Views 199–202
Young Gorilla Walking To face 208
Native Carrier Boy " 222
Native Women of the
"
Interior 230
GORILLAS AND CHIMPANZEES
CHAPTER I

MAN AND APE COMPARED

Monkeys have always been a subject of idle interest to old and


young; but they have usually served to amuse the masses more
than to instruct them, until within recent years.
Now that science has brought them within the field of careful
research, and made them an object of serious study, it has invested
them with a certain dignity in the esteem of mankind, and imparted
to them a new aspect among animals.
There is no other creature that so charms and fascinates the
beholder as do these little effigies of the human race. The simple
and the wise are alike impressed with their human look and manner;
children and patriarchs with equal delight watch them with surprise;
but now that the search-light of science is being thrown into every
nook and crevice of nature, human interest in them is multiplied
many fold, while the savants of all civilised lands are struggling with
the problem of their possible relationship to man.
Pursuant to the desire of learning as much as possible about
their natural habits, faculties, and resources, they are being studied
from every available point of view, and every characteristic
compared in detail to the corresponding one in man. Hence, in order
to appreciate more fully the value of the lessons to be drawn from
the contents of this volume, we must know the relative planes in the
scale of nature that man and monkeys occupy, wherefore we shall
begin our task by comparing them in a general way; but as the
scope of this work is restricted mainly to the great apes, the
comparison will likewise be confined to that subject, except in so far
as to define the relations of man and ape to monkeys.
Since monkeys differ among themselves so widely, it is evident
that all of them cannot in the same degree resemble man. And as
the degree of interest in them as a subject of comparative study is
approximately measured by the degree of their likeness to man, it is
apparent that all cannot be regarded as of equal interest. But since
each forms an integral part of the scale of nature, they are of equal
importance in tracing out the continuity of the order to which they
belong.
The vast family of simians has perhaps the widest range of types
of any single family of mammals. Beginning with the great apes,
which so closely resemble man in size, form and structure, they
descend by degrees along the scale till they end in the little
marmosets, which are almost on the level of rodents. But the
descent is so gradual that it is difficult to draw a sharp line of
demarcation at any point between the two extremes. There is,
however, now an effort being made to separate this family into
smaller groups, but the lines between them must be dim and
wavering, and the literature of the past has a tendency to retard the
effort.
We shall not digress from the trend of our subject, however, at
this time, to discuss the problems with which zoology may have to
contend in the future, but will accept the current system and
proceed.
All the varied types that belong to the simian family are, in the
common order of speech, known as monkeys, but the term thus
used is so broad in its meaning as to include all the forms of that
vast group, wherefore it is vague and obscure, for some of these
resemble man more than they resemble each other. The name
should only be applied to those having tails and short faces, but
there is a small group, which have no tails at all, that are properly
known as apes. While they are all simians, they are not all monkeys.
It is with this small group, without tails, that we propose chiefly to
deal. We select them because of their likeness to man, and having
noted the similitude, the result may be compared with other types of
the same order. There are only four of these apes, but as a whole
they resemble man in so many essential details that they are called
"anthropoid," or "man-like apes." They differ from each other in
certain respects, almost as much as any one of them differs from
man. The four apes alluded to, are the chimpanzee, the gorilla, the
orang and the gibbon.
As the skeleton is the framework of the physical structure, it will
serve as the basis upon which to build up the comparison, and as
the chimpanzee is the nearest approach to man, we select him as
the highest type of the simian, and use him as the standard.
The skeleton of the chimpanzee may be said to be exactly the
same as that of man, but the assertion must be qualified by a few
facts which are of minor importance, but since they are facts we
cannot ignore them.
The general plan, purpose and principle are the same in each.
There is no part of the one that is not duplicated in the other, and
there is no function discharged by any part of the one that is not
discharged by the like part of the other. The chief point in which they
differ is in the structure of one bone.
Near the base of the spinal column is a certain bone called the
sacrum. It is a constituent part of the column, but in its singular
form and structure somewhat differs from the corresponding bone in
man. The general outline of this bone in the plane of the hips is that
of an isosceles triangle. It fits in between the two large bones that
spread out towards the hips, and articulate with the thighbones.
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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like