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

Introducing Functional Programming Using C# : Leveraging a New Perspective for OOP Developers Vaskaran Sarcar instant download

The document promotes the book 'Introducing Functional Programming Using C#' by Vaskaran Sarcar, which aims to help developers transition from object-oriented programming to functional programming using C#. It outlines the book's structure, prerequisites for readers, and the tools required for effective learning, emphasizing the importance of continuous learning in programming. Additionally, it provides links to download the book and other related resources from ebookmass.com.

Uploaded by

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

Introducing Functional Programming Using C# : Leveraging a New Perspective for OOP Developers Vaskaran Sarcar instant download

The document promotes the book 'Introducing Functional Programming Using C#' by Vaskaran Sarcar, which aims to help developers transition from object-oriented programming to functional programming using C#. It outlines the book's structure, prerequisites for readers, and the tools required for effective learning, emphasizing the importance of continuous learning in programming. Additionally, it provides links to download the book and other related resources from ebookmass.com.

Uploaded by

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

Visit https://ebookmass.

com to download the full version and


browse more ebooks or textbooks

Introducing Functional Programming Using C# :


Leveraging a New Perspective for OOP Developers
Vaskaran Sarcar

_____ Press the link below to begin your download _____

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

Access ebookmass.com now to download high-quality


ebooks or textbooks
We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmass.com
to discover even more!

Introducing Functional Programming Using C#: Leveraging a


New Perspective for OOP Developers 1st Edition Vaskaran
Sarcar
https://ebookmass.com/product/introducing-functional-programming-
using-c-leveraging-a-new-perspective-for-oop-developers-1st-edition-
vaskaran-sarcar/

Introducing ReScript: Functional Programming for Web


Applications 1st Edition Danny Yang

https://ebookmass.com/product/introducing-rescript-functional-
programming-for-web-applications-1st-edition-danny-yang/

Simple and Efficient Programming with C#: Skills to Build


Applications with Visual Studio and .NET 2nd Edition
Vaskaran Sarcar
https://ebookmass.com/product/simple-and-efficient-programming-with-c-
skills-to-build-applications-with-visual-studio-and-net-2nd-edition-
vaskaran-sarcar/

Simple and Efficient Programming with C# : Skills to Build


Applications with Visual Studio and .NET 2nd Edition
Vaskaran Sarcar
https://ebookmass.com/product/simple-and-efficient-programming-with-c-
skills-to-build-applications-with-visual-studio-and-net-2nd-edition-
vaskaran-sarcar-2/
Modern C++ for Absolute Beginners: A Friendly Introduction
to the C++ Programming Language and C++11 to C++23
Standards, 2nd Edition Slobodan Dmitrovi■
https://ebookmass.com/product/modern-c-for-absolute-beginners-a-
friendly-introduction-to-the-c-programming-language-
and-c11-to-c23-standards-2nd-edition-slobodan-dmitrovic/

Options and Derivatives Programming in C++23: Algorithms


and Programming Techniques for the Financial Industry, 3rd
Edition Carlos Oliveira
https://ebookmass.com/product/options-and-derivatives-programming-
in-c23-algorithms-and-programming-techniques-for-the-financial-
industry-3rd-edition-carlos-oliveira/

Programming: Principles and Practice Using C++ , Second


Edition Stroustrup

https://ebookmass.com/product/programming-principles-and-practice-
using-c-second-edition-stroustrup/

Data Parallel C++ : Programming Accelerated Systems Using


C++ and SYCL James Reinders

https://ebookmass.com/product/data-parallel-c-programming-accelerated-
systems-using-c-and-sycl-james-reinders/

Programming: Principles and Practice Using C++ 2nd


Edition, (Ebook PDF)

https://ebookmass.com/product/programming-principles-and-practice-
using-c-2nd-edition-ebook-pdf/
Vaskaran Sarcar

Introducing Functional Programming


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

ISBN 978-1-4842-9696-7 e-ISBN 978-1-4842-9697-4


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

© Vaskaran Sarcar 2023

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress


Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
This book is dedicated to all those developers who want to improve their
applications and do not give up easily.
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.
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, 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.
Who Is This Book For?
In short, read this book if you answer “yes” to the following questions:
Are you familiar with .NET, C#, and basic object-oriented concepts
such as polymorphism, inheritance, abstraction, and encapsulation?
Are you familiar with some of the advanced concepts in C# such as
delegates, lambda expressions, and generics?
Do you know how to set up your coding environment?
Do you want to develop your functional programming skills?
Are you interested in knowing how the core constructs of C# can
help you in FP?
You probably shouldn’t pick this book if the answer is “yes” to any of
the following questions:
Are you looking for a C# tutorial or reference book?
Are you not ready to experiment with FP with a programming
language that was primarily developed for OOP?
Do you despise Windows, Visual Studio, or .NET?

Useful Software
These are the important tools that I use in this book:
While writing this book, I had the latest edition of Visual Studio
Community 2022 (64-bit, version 17.5.4). All the programs were
tested with C# 11 and .NET 7.
Nowadays the C# language version is automatically selected based
on your project’s target framework(s) so that you can always get the
highest compatible version by default. In the latest versions, Visual
Studio doesn’t allow the UI to change the value, but you can change it
by editing the .csproj file.
As per a new rule, C# 11 is supported only on .NET 7 and newer
versions. C# 10 is supported only on .NET 6 and newer versions. C# 9
is supported only on .NET 5 and newer versions. C# 8.0 is supported
only on .NET Core 3.x and newer versions. If you are interested in the
C# language versioning, you can visit
https://docs.microsoft.com/en-
us/dotnet/csharp/language-reference/configure-
language-version.
The community edition is free of cost. If you do not use the Windows
operating system, you can still use the free Visual Studio Code, which
is a source-code editor developed by Microsoft to support Windows,
Linux, or Mac operating systems. At the time of this writing, Visual
Studio 2022 for Mac is also available, but I did not test my code on it.

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).
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.
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.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit https://www.apress.com/gp/services/source-code.
Acknowledgments
I thank the Almighty. I sincerely believe that only with His blessings
could I complete this book. I also extend my deepest gratitude and
thanks to the following people:
Leandro Fernandes Vieira and Paul Louth: They allowed me to use
the Curryfy library and language-ext library in this book. Leandro
also joined the technical review team and provided many useful
suggestions and improvements for this book.
Shekhar Kumar Maravi: Shekhar was another technical reviewer
for this book. He has been reviewing my books since 2015. Whenever
I am in need, he provides me with support. Thank you one more time.
Smriti, Laura, and Mark: Thanks to each of you for giving me
another opportunity to work with you and Apress.
Shon, Kim, Nagarajan, and Vinoth: Thanks to each of you for your
exceptional support to improve my work.
Finally, I thank those people from the functional programming
community who have shared their knowledge through online blogs,
articles, courses, and books.
Table of Contents
Part I: Getting Familiar with Functional Programming
Chapter 1:​Functional Programming Overview
C# Supports Multiple Paradigms
Functions and Methods Are Equivalent in C#
Important Characteristics of FP
FP Treats Functions as First-Class Citizens
FP Prefers Immutability
FP Prefers Pure Functions
FP Follows a Declarative Style
FP vs.​OOP
FP Benefits
Exercises
Summary
Solutions to Exercises
Chapter 2:​Understanding Functions
Mathematical Background of Functions
Mathematical Functions vs.​C# Functions
Representing Functions in C#
Using Static Methods
Using Delegates and Lambdas
Using a Dictionary
Built-in Delegates Are Important
Higher-Order Function
Custom HOF
Built-in HOF
First-Order Function
Refactoring Impure Functions
Program with Impurities
Removing Impurities
Exercises
Summary
Solutions to Exercises
Chapter 3:​Understanding Immutability
What Is Immutability?​
Immutable Objects in .​NET
Reviewing Mutable Types
Programming with a Mutable Type
The Path Toward Immutability
Achieving External Immutability
Enforcing Internal Immutability
Better Code Using Modern Features
More on Immutability
Understanding Shallow Immutability
Searching for a Solution
Making a Better Solution
Implementing Popsicle Immutability
Exercises
Summary
Solutions to Exercises
Part II: Harnessing the Power of Functional Programming
Chapter 4:​Composing Functions Using Pipelining
Overview
Coding Functional Composition
Importance of Chaining Functions
Program Without Chaining Functions
Refactoring Using Chaining Functions
Applying Composition
Using Pipelining
Using HOFs
Exercises
Summary
Solutions to Exercises
Chapter 5:​Composing Functions Using Currying
Overview of Currying
Program Without Currying
Using the Concept of Currying
Using External NuGet Packages
Using Curryfy
Exercises
Summary
Solutions to Exercises
Chapter 6:​Handling Temporal Coupling
Temporal Coupling Overview
How Does This Happen?​
Recognizing the Problem
A Program That Suffers from Temporal Coupling
Removing the Effect
A Better Program
Exercises
Summary
Solutions to Exercises
Chapter 7:​Functional Patterns
Map Pattern
Understanding the Problem
Initial Solution
Better Solution
Concise Solution
Select As Map
Introducing Functors
Conclusion
Bind Pattern
Understanding the Problem
Initial Solution
FP-Based Solution
SelectMany As Bind
What About Monads?​
Conclusion
Filter Pattern
Understanding the Problem
Initial Solution
Where As Filter
Fold Pattern
Understanding the Problem
Solutions Using Built-in Functions
Conclusion
Revisiting ForEach
Exercises
Summary
Solutions to Exercises
Chapter 8:​Exception Handling
Reviewing Exception Handling in OOP
Imperative Style of Programming
Exception Handling in FP
Using language-ext
Introducing the Either Type
Handling a Single Exception
Handling Multiple Exceptions
Chaining Exceptions
Handling Null Values
Introducing the Option Type
Exercises
Summary
Solutions to Exercises
Chapter 9:​Miscellaneous Topics
Helpful Features for FP
Delegates and Lambdas
Anonymous Methods
Extension Methods and LINQ
Type Inference
Importing Static Members
Immutability Features
Expression-Bodied Members
Local Functions
Tuples
Pattern Matching
Revisiting Option<T>
Bind Function
Return Function
Introducing Monads
Definition
Mathematical Background
Monad Laws
Chaining Multi-argument Functions
Final Suggestions
Command Query Separation
Learn Design Patterns and Anti-Patterns
Don’t Let Failures Stop You
How Much Functional Code Do I Need?​
Applications of FP
The Road Ahead
Exercises
Summary
Solutions to Exercises
Appendix:​Recommended Resources
Index
About the Author
Vaskaran Sarcar
obtained his master’s degree in software
engineering from Jadavpur University,
Kolkata (India), and his master’s of
computer application from Vidyasagar
University, Midnapore (India). He was a
National Gate Scholar (2007–2009) and
has more than 12 years of experience in
education and the IT industry. He
devoted his early years (2005–2007) to
the teaching profession at various
engineering colleges, and later he joined
HP India PPS R&D Hub in Bangalore. He
worked at HP until August 2019. At the
time of his retirement from HP, he was a senior software engineer and
team lead. Vaskaran is following his passion and is now a full-time
author. You can find him on LinkedIn at
https://www.linkedin.com/in/vaskaransarcar and see all
of his books at
https://amazon.com/author/vaskaran_sarcar.
About the Technical Reviewers
Leandro Fernandes Vieira
is a senior software engineer currently
working for a leading payment solutions
company. He earned his degree in system
analysis and development from Sã o
Paulo State Technological College
(FATEC-SP), Brazil. His realm of
expertise includes the .NET stack and the
C# and F# programming languages. He
has a passion for programming and
algorithms and likes to contribute to
open-source projects; in fact, he is a
creator of the RecordParser project, one
of the fastest CSV parsers for .NET.
He enjoys spending time with his family, walking in the park, hitting
the gym, and listening to heavy-metal music.
You can reach him at https://github.com/leandromoh/.

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
Part I
Getting Familiar with Functional
Programming
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.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer
Nature 2023
V. Sarcar, Introducing Functional Programming Using C#
https://doi.org/10.1007/978-1-4842-9697-4_1

1. Functional Programming Overview


Vaskaran Sarcar1
(1) Kolkata, West Bengal, India

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

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.

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.

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.

FP Prefers Immutability
Immutability is a design choice, and it is one of the fundamental
principles of FP. In this context, I’d like to quote Microsoft again. The
online link https://learn.microsoft.com/en-
us/archive/msdn-magazine/2010/april/fsharp-basics-
an-introduction-to-functional-programming-for-net-
developers says the following:

Imperative programming emphasizes the use of mutable variables


whereas functional programming uses immutable values.

Chapter 3 of this book discusses many aspects of immutability. In


the .NET world, it means that once you initialize (or create) a type, you
should not change its internal state at a later stage. Immutability is a
big topic. For now, let’s have a quick review.
Author’s note In Chapter 3, you’ll see different variations of
immutability. But in every case, the core idea is the same: once you
make a type that does not allow continuous changes to its state (or the
state of its instances), it is considered immutable in some sense.

Demonstration 2
Suppose I have a program that starts with a list of names. Later, I clear
the content of this list and add new names. The following program
demonstrates this:

using static System.Console;

List<string> names = new() { "Sam", "Bob" };


WriteLine("The list includes the following
names:");
names.ForEach(x=> WriteLine(x));

// Removing existing names


names.Clear();
// Adding two new names
names.Add("Kate");
names.Add("Jack");

WriteLine("\nThe list includes the following


names:");
names.ForEach(x => WriteLine(x));

Note Removing the lambda expression, you can simply the line
names.ForEach(x => WriteLine(x)); as
names.ForEach(WriteLine);.

Output
Let’s verify the output.

The list includes the following names:


Sam
Bob
The list includes the following names:
Kate
Jack
You can see that the list contained two names, Sam and Bob, in the
beginning. Later I cleared the content of this list and added two new
names. This kind of update is called a destructive update because you
have lost the original content. The situation can be worse if you
encounter runtime exceptions. FP does not like this. It prefers
immutability. The key idea is that once created, variables should not
be reassigned or modified.
Now think for a moment: if you work on immutable variables, you
know that once initialized, these variables cannot change their values.
So, the term variable does not make sense in those contexts. This is the
reason you will hear the term value instead of variable in
functional programming.

Q&A Session
1.2 How does immutability fit into functional programming?
Immutability prevents nasty bugs from implicit dependencies,
destructive updates, and state mutations. These are aligned with FP’s
goal. Immutable types are thread-safe; therefore, in a multithreaded
environment, they make your programming life easy. Shortly, you’ll
learn about pure functions and side effects. Then you’ll understand that
these immutable types can help you avoid side effects too. In Chapter 6,
you’ll see that immutable types are also useful to avoid temporal
coupling. There are many more benefits; once you finish this book,
you’ll be able to find those benefits in other areas as well.

1.3 While discussing destructive updates, you said that the


situation becomes worse if you encounter runtime exceptions. Can
you give an example to demonstrate such a situation?
Consider Demonstration 3.

Demonstration 3
To answer the previous question (1.3), I’m going to modify
Demonstration 2. Let’s assume that the program needs to display the
names along with the number of characters that are present in the
name. The following is a typical implementation that contains a
possible bug. Why is there a possible bug? I start with a list of names
called names, and then I use the following code segment in this
program:

int random = new Random().Next(0, 2);


string? newName = random > 0 ? "Jack": null;
// Adding a new name
names.Add(newName);
You can see that before I add a name to the list, I generate a random
number. If the number is greater than 0, I’ll add this name; otherwise,
I’ll add a null. (Yeah, I know, it is bad! But I want to produce the bug
easily.)
Here is the complete program (notice the important changes in
bold):

using static System.Console;

WriteLine("Analyzing destructive updates.");

List<string> names = new() { "Sam", "Bob" };


WriteLine("The list includes the following:");
names.ForEach(x => WriteLine($"Name: {x},length:
{x.Length}"));

int random = new Random().Next(0, 2);


string? newName = random > 0 ? "Jack": null;
// Adding a new name
names.Add(newName);
WriteLine("\nThe list includes the following
names:");
names.ForEach(x => WriteLine($"Name: {x},length:
{x.Length}"));

Output
Here is some sample output when everything goes well and it was able
to add a new name successfully:

Analyzing destructive updates.


The list includes the following:
Name: Sam,length:3
Name: Kate,length:4

The list includes the following names:


Name: Sam,length:3
Name: Kate,length:4
Name: Jack,length:4

But based on the generated random number (when it is 0), this


program can throw the following runtime exception:

System.NullReferenceException: 'Object reference


not set to an instance of an object.'
x was null.

Analysis
This program shows that a destructive update can raise a runtime error.
As developers, we do not like to see a program crash at runtime. FP’s
philosophy is simple: avoid destructive updates. When I discuss
immutability in depth in Chapter 3, you’ll see that we can avoid this
kind of update in our program.

FP Prefers Pure Functions


FP wants you to use pure functions as much as possible. Microsoft (see
https://learn.microsoft.com/en-
us/dotnet/standard/linq/refactor-pure-functions)
echoes this by saying the following:

The common nomenclature in functional programming is that you


refactor programs using pure functions.
Which functions are pure? The previous link states that a function
is pure if it satisfies the following characteristics:
It’s consistent. Given the same set of input data, it will always return
the same output value.
It has no side effects. The function does not change any variables or
data of any type outside of the function.
The function that does not satisfy any of these conditions is called
an impure function.

Demonstration 4
You will learn more about purity and side effects shortly. For now, it will
be sufficient if you understand the following program:

using static System.Console;

WriteLine(AddFiveTo(2));
WriteLine(GetRandomNumber(2));

static int AddFiveTo(int input)


{
return input + 5;
}
static int GetRandomNumber(int input)
{
Random random = new();
return random.Next(input, input + 5);
}

Output
Here are some probable outputs from this program:

Sample Output-1:
7
3
Sample Output-2:
7
6
Sample Output-3:
7
4
And so on. You can see that given input 2, GetRandomNumber
returns different values. Since the result is inconsistent, you can
conclude that this is an impure function.
Now, look into the AddFive function. You can see that AddFiveTo
is consistent; it always returns 7 if the input is 2. You can also see that
this function depends on the supplied input only; it does not change
any variables or data of any type outside of the function. So, this
function does not have any side effect. Since both conditions for purity
are satisfied, we can conclude that AddFiveTo is a pure function.

Discussion of Side Effects


Let’s discuss side effects. Look at the following possibilities:
Case 1: Your function keeps modifying a static variable.
Case 2: You modify the function argument by passing a parameter as
a reference.
Case 3: Your function raises an exception for certain cases.
Case 4: Your function accepts user input and prints some message in
a console window.
The first two cases are easy to understand: they cause side effects.
Why? In each case, you mutate the values. As a result, given the same
input, the same function produces different outputs. You may still
wonder about case 3 and case 4. Let’s take a look at them.
To demonstrate case 3, I’ve written the following function inside the
Sample class. Obviously, it is bad.

class Sample
{
public static int GetResult(int a)
{
int random = new Random().Next(0,2);
return a / random;
}
}
The first problem is obvious: you cannot predict the result in
advance. For example, the following line:

int result = Sample.GetResult(6);

can give you valid data, or it can raise the following exception (when
the divisor random becomes 0):
System.DivideByZeroException: 'Attempted to divide
by zero.'
Throwing an exception always forces you to think about gracefully
handling the exception; otherwise, your program crashes, which is an
example of the worst possible side effect. In fact, exceptions indicate
indeterminism in the code.
I discuss case 4 in the section “Functions with I/O,” which is coming
next.

Functions with I/O


It should not be a surprise that a meaningful program often needs to
accept user input and display the output. So, you may be wondering, if a
function displays the output of a program, is it a side effect? Let’s
analyze this. If a function asks a user to pass a URL to display a
webpage, the result can vary when the internet connection becomes
unstable or the server is down. As a result, the same function can
potentially produce different results. In fact, thinking about the output
can make you even more uncomfortable. Consider the case when a
function queries a user by outputting text to the console something like
the following:

Console.WriteLine("Enter a number:");

Did you notice that the state of the system has changed, and
returning the system to its previous state is impossible now? You can
see that when a function needs to depend on the external world, there
is no escape. You may argue that this is an intended scenario, but
following the FP paradigm, it is still considered a side effect. In fact, a
purely mathematical function often needs to communicate the result
using the I/O. So, some of your code segments will have to be impure.
Now the next question is, which part of the code segments can be
impure? A common guideline for this type of situation is that you
should try to separate the functions that perform the I/O from the
functions that perform the actual computation. The functions that
perform those computations should be the pure function in the
functional world. In C#, we can mix them, but to follow a functional
style of coding, keep this suggestion in your mind.
In this book, I often compare OOP-style coding with an equivalent
functional style of coding with complete programs. When I refactor the
imperative code to functional code, I focus on the key aspects. Normally,
I do not change the Main method (aka function) that handles the I/O
operations. Remember, since I use top-level statements to demonstrate
programs, you will not explicitly see the presence of the Main method.
For example, in .NET 7, I can run a program that consists of a single line
as follows:

Console.WriteLine("Hello, reader!");

This is a big simplification compared to older versions of C#, where


you need to explicitly define the Main method and use the “using
statements” at the beginning of your file.
Author’s note If needed, you can learn about top-level statements
at https://learn.microsoft.com/en-
us/dotnet/csharp/whats-new/tutorials/top-level-
statements.

POINT TO NOTE
In the OOP style, it is a common practice to encapsulate data and
methods inside a class. But in the functional style of coding, it is
common to separate the functions from the data. The discussion of
side effects should give you the idea that FP encourages us to work
on pure functions and minimize the side effects.

Are Side Effects Bad?


Up until now we have been discussing function purity following the
formal definition. Now the question is, are impure functions
acceptable? Here are my thoughts on them:
We make assumptions about purity to some extent. This is because
any function can fail because of some factors that are beyond our
control. Consider the case of the “out of memory” error when your
code did not cause the error, but it came from someone else’s code,
which was executing in a parallel environment. Or, consider the case
when the operating system (OS) itself crashes. If you consider cases
like this, no function is 100 percent pure, and this is the sad truth! So,
when we talk about side effects, we ignore the factors that are
beyond our control.
Impurity does not always indicate something bad. Also, side effects
are often desirable in certain places. To illustrate this, let’s consider
the example of a database update or consider the case where you
work with a function that logs data including the current date and
time. What do you think about these operations? You understand that
to bring the theoretical “concept of purity,” you cannot introduce
unwanted complexities and compromise the overall performance of
your program.
The key idea is that you should avoid side effects as much as
possible to make your code more maintainable. For example, you can
isolate the I/O operations from the actual computations. (You will learn
more about this in Chapter 6 when I discuss the Functional Core,
Imperative Shell pattern.) Keeping a similar goal in mind, when you
refactor a code where the user interface (UI) layer talks to the business
logic layer, you first attempt to minimize the side effects in the business
logic layer.

POINT TO REMEMBER
In the context of purity and side effects, you can remember the
following points:
Any side effect indicates a visible “state change” of a program.
A pure function is “pure” to some extent. We cannot avoid all
possible circumstances. For example, during an execution of a C#
function, an exception can be thrown because of various factors.
Typical examples include insufficient memory or any other
operating system errors.
This means we cannot control every possible side effect. In
general, you should focus on those parts that you can control.
Finally, you should not conclude that an impure function is a bad
thing. In OOP, you probably have seen that we want dynamic
behavior in many applications, and that behavior is very much
desirable there. In fact, a normal program that tries to update a
database has a “desirable” side effect. Here we are studying pure
functions following the formal definitions, and this is the reason
we are focusing on purity. As you progress on this topic, these
topics will be clearer to you.

Q&A Session
1.4 Why does FP like pure functions?
There are many reasons behind this. Let me show you some of those
benefits:
Since these functions result in the same output, you can write test
cases against a consistent or reliable output.
This consistent nature can provide you with huge benefits when you
focus on parallelization.
In fact, once you get the result from an execution of a pure function,
you can avoid the further execution of this function. This is because,
once computed, this computed value will not change anymore.

1.5 Why do FP developers try to avoid side effects?


Side effects can change program states. This characteristic can
compromise the correctness of the code. In addition, a method that has
side effects does not depend entirely on program inputs. Because of
this, it is difficult to predict the program’s behavior in advance. So, these
side effects compromise the understandability of the code too. In
addition, if you work in a multithreaded environment and have
methods that cause side effects, you need to worry about thread
synchronizations. It is because you know that mutable variables lead to
implicit dependencies and can cause a lot of nasty bugs, particularly in
a concurrent program.

FP Follows a Declarative Style


Functional programming follows the declarative style of coding. What
does this mean? A declarative style focuses on “What do we want?”
instead of saying something like “Do this step, then do that step to get
the result.” When you mention a step-by-step approach to solving a
problem, the approach is imperative, not declarative. So, the imperative
style of programming describes how to solve the problem. The
following statements will make the concept clearer to you:
Imperative programming approach: Traverse the employee list
sequentially. If the employee’s age is 30 or more, show the
employee’s detail.
Declarative (functional) programming approach: From a given
list, display the details of the employees who are 30 years or older.

Demonstration 5
I will now show you a sample program that follows an imperative style
of coding. OOP developers are quite familiar with this style. Given a list
of numbers, the following program picks the numbers that are greater
than 30 (notice the important segment in bold):

using static System.Console;

WriteLine("Using an imperative style of coding.");


List<int> numbers = new() { 10, 20, 30, 40, 50 };
// Imperative style
WriteLine("The list includes the following:");
foreach (int number in numbers)
{
Write(number + "\t");
}
WriteLine("\nAges that are more than 30:");
foreach (int number in numbers)
{
if (number > 30)
{
Write(number + "\t");
}
}

Output
This program produces the following output:

Using an imperative style of coding.


The list includes the following:
10 20 30 40 50
Ages that are more than 30:
40 50

Now let’s see how a functional programmer can write an equivalent


program. Functional programmers like to use expressions, not
statements. Why? This choice makes the code more declarative.
Probably you know that System.Linq in C# is functional in nature.
So, a functional programmer may like to use the built-in support and
refactor the previous program; this is shown in the following
demonstration.

Demonstration 6
Here is the refactored program (notice the important changes in bold):

using static System.Console;

WriteLine("Using the declarative style of


coding.");
List<int> numbers = new() { 10, 20, 30, 40, 50 };
WriteLine("The list includes the following:");
numbers.ForEach(x => Write(x + "\t"));
WriteLine("\nAges that are more than 30:");
numbers.Where(x => x > 30)
.Select(x => x)
.ToList()
.ForEach(x => Write(x + "\t"));

Output
It should be no surprise that you see an equivalent output (that you saw
in Demonstration 5):

Using the declarative style of coding.


The list includes the following:
10 20 30 40 50
Ages that are more than 30:
40 50

Q&A Session
1.6 You said that FP developers prefer the declarative style of
coding. Do you think that the declarative style is better than the
imperative style?
No. Each approach has its pros and cons. Remember that our goal is to
take the best from each approach.
Let’s see the advantages of the declarative style of coding. The
imperative style instructs how to perform the computation, so the
order of execution of the statements is important. But the declarative
style focuses on what to be computed, not on “how it’s to be computed.”
So, it helps you vary the function invocation calls. For example,
given the list shown in the previous demo, each of the following code
segments (segment-1 and segment-2) will produce the identical result
(notice that I have altered the function calls in the top two lines in these
segments):

// Segment-1
numbers.Where(x => x > 30)
.Select(x => x)
.ToList()
.ForEach(x => Write(x + "\t"));

// Segment-2
numbers.Select(x => x)
.Where(x => x > 30)
Other documents randomly have
different content
The Project Gutenberg eBook of The Life of
Captain Sir Richard F. Burton, volume 1 (of 2)
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

Title: The Life of Captain Sir Richard F. Burton, volume 1 (of 2)

Author: Lady Isabel Burton

Release date: April 20, 2017 [eBook #54578]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by Clare Graham and Marc D'Hooghe at Free


Literature (online soon in an extended version, also
linking
to free sources for education worldwide ... MOOC's,
educational materials,...) Images generously made
available
by the Internet Archive.

*** START OF THE PROJECT GUTENBERG EBOOK THE LIFE OF


CAPTAIN SIR RICHARD F. BURTON, VOLUME 1 (OF 2) ***
THE LIFE OF
CAPTAIN

SIR RICHARD F. BURTON,


K.C.M.G., F.R.G.S.

BY HIS WIFE,
ISABEL BURTON.
WITH NUMEROUS PORTRAITS,
ILLUSTRATIONS, AND MAPS.
IN TWO VOLUMES.
VOL. I.

LONDON: CHAPMAN & HALL, LD.


1893.
RICHARD BURTON IN HIS TENT IN AFRICA.

CONSECRATION.

TO MY EARTHLY MASTER,

WHO IS WAITING FOR ME ON HEAVEN'S FRONTIERS.

Whilst waiting to rejoin you, I leave as a message to the World we


inhabited, the record of the Life into which both our lives were
fused. Would that I could write as well as I can love, and do you
that justice, that honour, which you deserve! I will do my best, and
then I will leave it to more brilliant pens, whose wielders will feel
less—and write better.
Meet me soon—I wait the signal!
ISABEL BURTON.

FOREWORD.
"No man can write a man down except himself."

In speaking of my husband, I shall not call him "Sir Richard," or


"Burton," as many wives would; nor yet by the pet name I used for
him at home, which for some reason which I cannot explain was
"Jemmy;" nor yet what he was generally called at home, and what
his friends called him, "Dick;" but I will call him Richard in speaking
of him, and "I" where he speaks on his own account, as he does in
his private journals. I always thought and told him that he destroyed
much of the interest of his works by hardly ever alluding to himself,
and now that I mention it, people may remark it, that in writing he
seldom uses the pronoun I. I have therefore drawn, not from his
books, but from his private journals. It was one of his asceticisms,
an act of humility, which the world passed by, and probably only
thought one of his eccentricities. In his works he would generally
speak of himself as the Ensign, the Traveller, the Explorer, the
Consul, and so on, so that I often think that people who are not
earnest readers never understood who it was that did this, thought
that, or saw the other. If I make him speak plainly for himself, as he
does in his private journals, but never to the public, it will give
twenty times the interest in relating events; so I shall throughout let
him speak for himself where I can.
In early January, 1876, Richard and I were on our way to India for a
six months' trip to visit the old haunts. We divided our intended
journey into two lots. We cut India down the middle, the long way
on the map, from north to south, and took the western side, leaving
the eastern side for a trip which was deferred, alas! for our old age
and retirement. We utilized the voyage out (which occupied thirty-
three days in an Austrian Lloyd, used as a Haj, or pilgrim-ship), and
also the voyage back, in the part of the following pages which refers
to his early life, he dictating and I writing.
In 1887, when my husband was beginning to be a real invalid, he
lent some of these notes to Mr. Hitchman (who asked leave to write
his biography), Richard promising not to tread upon his heels by his
own Autobiography till he should be free from service in 1891. It will
not, I think, do any harm to the reading public to reproduce it with
more detail, because only seven hundred people got Mr. Hitchman's,
who did not by any means use the whole of the material before he
returned it, and what I give is the original just as Richard dictated it,
and it is more needful, because it deals with a part of his life that
was only known to himself, to me only by dictation; because
everything that he wrote of himself is infinitely precious, and
because to leave to the public a sketch of an early Richard Burton is
desirable, otherwise readers would be obliged to purchase Mr.
Hitchman's, as well as this work, in order to make a perfect whole.
I must take warning, however, that when Mr. Hitchman's book came
out, part of the Press found this account of my husband's boyhood
and youth charming, and another part of the Press said that I was
too candid, and did nothing to gloss over the faults and foibles of
the youthful Burtons; they doubted the accuracy of my information—
I was informed that my style was too rough-and-ready, and of many
others of my shortcomings. In short, I was considered rather as
writing against my own husband, whilst both sides of the Press in
their reviews assumed that I wrote it; this charmed Richard, and he
would not let me refute. Not one word was mine—it was only
dictation, and peremptory dictation when I objected to certain self-
accusations. I beg leave to state that I did not write one single
word; I could not, for I did not know it—and all that the family
objected to, or considered exaggerated, will not be repeated here.
Before entering on these pages, I must warn the reader not to
expect the goody-goody boy nor yet the precocious vicious youth of
1893. It is the recital of a high-spirited lad of the old school, full of
animal spirits and manly notions, a lively sense of fun and humour,
reckless of the consequences of playing tricks, but without a vestige
of vice in the meaner or lower forms—a lad, in short, who would be
a gentleman and a man of the world in his teens, and who, from his
foreign travel, had seen more of life than boys do brought up at
home.
I do not begin this work—the last important work of my life—without
fear and trembling. If I can perform this sacred duty—this labour of
love—well,—I shall be glad indeed, but I begin it with unfeigned
humility. I have never needed any one to point out to me that my
husband was on a pedestal far above me, or anybody else in the
world. I have known it from 1850 to 1893, from a young girl to an
old widow, i.e. for forty-three years. I feel that I cannot do justice to
his scientific life, that I may miss points in travel that would have
been more brilliantly treated by a clever man. My only comfort is,
that his travels and services are already more or less known to the
public, and that other books will be written about them. But if I am
so unfortunate as to disappoint the public in this way, there is one
thing that I feel I am fit for, and that is to lift the veil as to the inner
man. He was misunderstood and unappreciated by the world at
large, during his life. No one ever thought of looking for the real
man beneath the cultivated mask that generally hid all feelings and
belief—but now the world is beginning to know what it has lost. The
old, old, sad story.
He shall tell his own tale till 1861, the first forty years, annotated by
me. Whilst dictating to me I sometimes remarked, "Oh, do you think
it would be well to write this?" and the answer always was, "Yes! I
do not see the use of writing a biography at all, unless it is the exact
truth, a very photograph of the man or woman in question." On this
principle he taught me to write quite openly in the unconventional
and personal style—being the only way to make a biography
interesting, which we now class as the Marie Bashkirtcheff style. As
you will see, he always makes the worst of himself, and offers no
excuse. As a lad he does not know what to do to show his
manliness, and all that a boy should, ought, and does think brave
and honourable, be it wild or not, all that he does.
What appals me is, that the task is one of such magnitude—the
enormous quantity of his books and writings that I have to look
through, and, out of eighty or more publications, to ascertain what
has seen the light and what has not, because it is impossible to
carry the work of forty-eight years in one's head; and, again, the
immense quantity of subjects he has studied and written upon, some
in only a fragmentary state, is wonderful. My wish would be to
produce this life, speaking only of him—and afterwards to reproduce
everything he has written that has not been published. I propose
putting all the heavier matter, such as pamphlets, essays, letters,
correspondence, and the résumé of his works—that is, what portion
shows his labours and works for the benefit of the human race—into
two after-volumes, to be called "Labours and Wisdom of Richard
Burton." After his biography I shall renew his "Arabian Nights" with
his Forewords, Terminal Essay, and Biography of the book in such
form that it can be copyrighted—it is now protected by my
copyright. His "Catullus" and "Pentamerone" are now more or less in
the Press, to be followed by degrees by all his unpublished works.
His hitherto published works I shall bring out as a Uniform Library,
so that not a word will be lost that he ever wrote for the public.
Fortunately, I have kept all his books classified as he kept them
himself, with a catalogue, and have separate shelves ticketed and
numbered; for example, "Sword," "Gypsy," "Pentamerone,"
"Camoens," and so on.
If I were sure of life, I should have wished for six months to look
through and sort our papers and materials before I began this work,
because I have five rooms full. Our books, about eight thousand,
only got housed in March, 1892, and they are sorted—but not the
papers and correspondence; but I fancy that the public would rather
have a spontaneous work sooner, than wait longer. If I live I shall
always go on with them. I have no leisure to think of style or of
polish, or to select the best language, the best English,—no time to
shine as an authoress. I must just think aloud, so as not to keep the
public waiting.
From the time of my husband's becoming a real invalid—February,
1887—whilst my constant thoughts reviewed the dread To Come—
the catastrophe of his death—and the subsequent suffering, I have
been totally incapable, except writing his letters or attending to his
business, of doing any good literary work until July, 1892, a period of
five years, which was not improved by four attacks of influenza.
Richard was such a many-sided man, that he will have appeared
different to every set of people who knew him. He was as a diamond
with so many facets. The tender, the true, the brilliant, the scientific,
—and to those who deserved it, the cynical, the hard, the severe.
Loads of books will be written about him, and every one will be
different; and though perhaps it is an unseemly boast, I venture to
feel sure that mine will be the truest one, for I have no interest to
serve, no notoriety to gain, belong to no party, have nothing to sway
me, except the desire to let the world understand what it once
possessed, what it has lost. With many it will mean I. With me it
means HIM.
When this biography is out, the public will, theoretically, but not
practically, know him as well as I can make them, and all of his
friends will be able after that to put forth a work representing that
particular facet of his character which he turned on to them, or
which they drew from him. He was so great, so world-wide, he could
turn a fresh facet and sympathy on to each world. I always think
that a man is one character to his wife at his fireside corner, another
man to his own family, another man to her family, a fourth to a
mistress or an amourette—if he have one,—a fifth to his men
friends, a sixth to his boon companions, and a seventh to his public,
and so on ad infinitum; but I think the wife, if they are happy and
love each other, gets the pearl out of the seven oyster-shells.
I fear that this work will be too long. I cannot help it. When I
embarked on it I had no conception of the scope: it was a labour of
love. I thought I could fly over it; but I have found that the more I
worked, the more it grew, and that the end receded from me like the
mirage in the desert. I only aim at giving a simple, true recital
without comment, and at fairness on all questions of whatever sort.
I am very personal, because I believe the public like it. I want to
give Richard as I knew him at home. I apologize in advance to my
readers if I am sometimes obliged to mention myself oftener than
they and I care about; but they will understand that our lives were
so interwoven, so bound together, that I should very often spoil a
good story or an anecdote or a dialogue were I to leave myself out.
It would be an affectation that would spoil my work.
I am rather disheartened by being told by a literary friend that the
present British public likes its reading "in sips." How can I give a life
of seventy years, every moment of which was employed in a
remarkable way, "in sips"? It is impossible. Though I must not detail
much from his books, I want to convey to the public, at least, what
they were about; striking points of travel, his schemes, wise
warnings, advice, and plans for the benefit of England—then what
about "sips"? It must not be dry, it must not be heavy, nor tedious,
nor voluminous; so it shall be personal, full of traits of character,
sentiments and opinions, brightened with cheerful anecdotes, and
the more serious part shall go into the before-mentioned two
volumes, the "Labours and Wisdom of Richard Burton."
I am not putting in many letters, because he generally said such
personal things, that few would like them to be shown. His business
letters would not interest. To economize time he used to get
expressly made for him the smallest possible pieces of paper, into
which he used to cram the greatest amount of news—telegram
form. He only wrote much in detail, if he had any literary business to
transact.
One of my greatest difficulties, which I scarcely know how to
express, is, that which I think the most interesting, and which most
of my intimates think well worth exploring; it is that of showing the
dual man with, as it were, two natures in one person, diametrically
opposed to each other, of which he was himself perfectly conscious.
I had a party of literary friends to dinner one night, and I put my
manuscript on the table before them after dinner, and I begged
them each to take a part and look over it. Feeling as I do that the
general public never understood him, and that his mantle after death
seemed to descend upon my shoulders, that everything I say seems
to be misunderstood, and that, in some few eyes, I can do nothing
right, I said at the end of the evening, "If I endeavour to explain,
will it not be throwing pearls to swine?" (not that I meant, dear
readers, to compare you to swine—it is but an expression of thought
well understood). And the answer was, "Oh, Lady Burton, do give
the world the ins and outs of this remarkable and interesting
character, and let the swine take care of themselves." "If you leave
out by order" (said one) "religion and politics, the two touchstones
of the British public, you leave out the great part of a man." "Mind
you gloss over nothing to please anybody" (said a second). I think
they are right—one set of people see one side, and another see
another side, and neither of the two will comprehend (like St.
Thomas) anything that they have not seen and felt; or, to quote one
of Richard's favourite mottoes from St. Augustine, "Let them laugh
at me for speaking of things which they do not understand, and I
must pity them, whilst they laugh at me." So I must remain an
unfortunate buffer amidst a cyclone of opinions. I can only avoid
controversies and opinions of my own, and quote his and his actions.
These words are forced from me, because I have received my
orders, if not exactly from the public, from a few of the friends who
profess to know him best. I am ordered to describe Richard as a sort
of Didérot (a disciple of Voltaire's), who wrote "that the world would
never be quiet till the last king was strangled with the bowels of the
last priest,"—whereas there was no one whom Richard delighted
more to honour than a worthy King, or an honest straightforward
Priest.
There are people who are ready to stone me, if I will not describe
Richard as being absolutely without belief in anything; yet I really
cannot oblige them, without being absolutely untruthful. He was a
spade-truth man, and he honestly used to say that he examined
every religion, and picked out its pearl to practise it. He did not scoff
at them, he was perfectly sincere and honest in what he said; nor
did he change, but he grew. He always said, and innumerable
people could come forward, if they had the courage—I could name
some—to say that they have heard him declare, that at the end of
all things there were only two points to stand upon—NOTHING and
CATHOLICISM; and many could, if they would, come forward and
say, that when they asked him what religion he was, he answered
Catholic.
He never was, what is called here and now in England, an Agnostic;
he was a Master-Sufi, he practised Tasáwwuf or Sufi-ism, which
combines the poetry and prose of religion, and is mystic. The Sufi is
a profound student of the different branches of language and
metaphysics, is gifted with a musical ear, indulges in luxuriant
imagery and description. They have a simple sense—a double
entendre understood amongst themselves—God in Nature,—Nature
in God—a mystical affection for a Higher Life, dead to excitement,
hope, fear, etc. He was fond of quoting Sayyid Mohammad Hosayn's
motto, "It is better to restore one dead heart to Eternal Life, than
Life to a thousand dead bodies."
I have seen him receive gratuitous copies of an Agnostic paper in
England, and I remember one in particular—I do not know who
wrote it,—it was very long, and all the verses ended with "Curse God
the Father, Son, and Holy Ghost." I can see him now reading it—and
stroking his long moustache, and muttering, "Poor devil! Vulgar
beast!" He was quite satisfied, as his friends say, that we are not
gifted with the senses to understand the origin of the Mysteries by
which we are surrounded, and in this nobody agrees more
thoroughly than I do. He likewise said he believed there was a God,
but that he could not define Him; neither can I, neither can you, but
I do not want to. Great minds tower above and see into little ones,
but the little minds never climb sufficiently high to see into the Great
Minds, and never did Lord Beaconsfield say a truer thing, speaking
of religion than when he said, "Sensible men never tell." As I want to
make this work both valuable and interesting, I am not going into
the unknown or the unknowable, only into what he knew—what I
know; therefore I shall freely quote his early training, his politics, his
Mohammedanism, his Sufi-ism, his Brahminical thread, his
Spiritualism, and all the religions which he studied, and nobody can
give me a sensible reason why I should leave out the Catholicism,
except to point the Spanish proverb, "that no one pelts a tree,
unless it has fruit on it," but were I to do so, the biography would be
incomplete.
Let us suppose a person residing inside a house, and another person
looking at the house from the opposite side of the street; you would
not be unjust enough to expect the person on the outside to
describe minutely its inner chambers and everything that was in it,
because he would have to take it on trust from the person who
resided inside, but you would take the report of the man living
outside as to the exterior of the house. That is exactly the same as
my writing my husband's history. Do you want an edition of the
inside or an edition of the outside? If you do not want the truth, if
you order me to describe a Darwin, a Spencer, a John Stuart Mill, I
can do it; but it will not be the home-Richard, the fireside-Richard
whom I knew, the two perfectly distinct Richards in one person; it
will be the man as he was at lunch, at dinner, or when friends came
in, or when he dined out, or when he paid visits; and if the world—
or, let us say, a small portion of the world,—is so unjust and silly as
to wish for untrue history, it must get somebody else to write it. To
me there are only two courses: I must either tell the truth, and lay
open the "inner life" of the man, by a faithful photograph, or I must
let it alone, and leave his friends to misrepresent him, according to
their lights.
It has been threatened to me that if I speak the truth I am to reap
the whirlwind, because others, who claim to know my husband well,
see him quite in a different light. (I know many people intimately,
but I am quite incompetent to write their lives—I am only fit to do
that for the man with whom I lived night and day for thirty years;
there are three other people who could each write a small section of
his life, and after those nobody; I do not accept the so-called
general term "friend.") I shall be very happy indeed to answer
anybody who attacks me, who is brave enough to put his or her
name; but during the two years I have been in England I have
hardly had anything but anonymous communications and paragraphs
signed under the brave names of "Agnostic," or "One who knows,"
so I have no man or woman to deal with, but empty air, which is
beneath my contempt. This is a very old game, perhaps even more
ancient than "Prophesy, O Christ, who it was that struck Thee!" but
it is cowardly and un-English—that is, if England "stands where she
did." I would also remind you of the good old Arab proverb, that "a
thousand curses never tore a shirt."
I would have you remember that I gain nothing by trying to describe
my husband as belonging to any particular religion. If I would
describe him as an English Agnostic—the last new popular word—the
small band of people who call themselves his intimate friends, and
who think to honour him by injuring me, would be perfectly satisfied.
I should have all their sympathy, and my name would be at rest,
both in Society and in the Press. I have no interest to serve in saying
he was a Catholic more than anything else; I have no bigotry on the
question at all. If he did something Catholic I shall say it, and if he
did something Mohammedan or Agnostic I shall equally say it.
It is also a curious fact, that the people who are most vexed with me
on this score, are men who, before their wives, mothers, sisters, are
good Protestants, and who go twice to the Protestant church on
Sundays, but who are quite scandalized that my husband should be
allowed a religion, and are furious because I will not allow that
Richard Burton was their Captain. No, thank you! it is not good
enough: he was not, never was like any of you—nor can I see what
it can possibly be to you what faith, or no faith, Richard Burton
chose to die in, and why you threaten me if I speak the truth! We
only knew two things—the beautiful mysticism of the East, which,
until I lived here, I thought was Agnosticism, and I find it is not; and
calm, liberal-minded Roman Catholicism. The difference between
you and Richard is—you, I mean, who admired my husband—that
you are not going anywhere,—according to your own Creed you
have nowhere to go to,—whilst he had a God and a continuation,
and said he would wait for me; he is only gone a long journey, and
presently I shall join him; we shall take up where we left off, and we
shall be very much happier even than we have been here.
Of the thousands that have written to me since his death, everybody
writes, "What a marvellous brain your husband had! How modest
about his learning and everything concerning himself! He was a man
never understood by the world." It is no wonder he was not
understood by the World; his friends hindered it, and when one who
knew him thoroughly, offers to make him understood, it is resented.
The Press has recently circulated a paragraph saying that "I am not
the fittest person to write my husband's life." After I have finished
these two volumes, it will interest me very much to read those of the
competent person, who will be so kind as to step to the front,—with
a name, please, not anonymously,—and to learn all the things I do
not know.
He, she, or it, will write what he said and wrote; I write what he
thought and did.
ISABEL BURTON.
29th May, 1893.

Note.—I must beg the reader to note, that a word often has several
different spellings, and my husband used to give them a turn all
round. Indeed, I may say that during the latter years of his life he
adopted quite a different spelling, which he judged to be correcter.
In many cases it is caused by the English way of spelling a thing,
and the real native way of spelling the same. For English Meeanee,
native way Miani. The battle of Dabba (English) is spelt Dubba,
Dubbah, by the natives. Fulailee river (English) is spelt Phuleli
(native). Mecca and Medina have sometimes an h at the end of
them. Karrachee is Karáchi. Sind is spelt Sind, Sindh, Scind, Scinde;
and what the Anglo-Indians call Bóbagees are really Babárchis, and
so on. I therefore beg that the spelling may not be criticized. In
quoting letters, I write as the author does, since I must not change
other people's spelling.—I. B.
[Transcriber's Note.—The page headings of the original edition have been converted into
sidenotes in this digital edition. Typographical and other obvious errors have also been
corrected, but the variations in the spelling of proper names, etc., mentioned above
remain.]
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like