100% found this document useful (3 votes)
25 views

Get (Ebook) Learning F# Functional Data Structures and Algorithms by Masood, Adnan ISBN 9781783558476, 1783558474 free all chapters

The document provides information about the ebook 'Learning F# Functional Data Structures and Algorithms' by Adnan Masood, including its ISBN, download link, and a brief overview of its content. It covers functional programming principles, data structures, algorithms, and practical applications in F#. Additionally, it includes recommendations for other related ebooks available for download on the same site.

Uploaded by

eloahblashhy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
25 views

Get (Ebook) Learning F# Functional Data Structures and Algorithms by Masood, Adnan ISBN 9781783558476, 1783558474 free all chapters

The document provides information about the ebook 'Learning F# Functional Data Structures and Algorithms' by Adnan Masood, including its ISBN, download link, and a brief overview of its content. It covers functional programming principles, data structures, algorithms, and practical applications in F#. Additionally, it includes recommendations for other related ebooks available for download on the same site.

Uploaded by

eloahblashhy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Visit https://ebooknice.

com to download the full version and


explore more ebooks

(Ebook) Learning F# Functional Data Structures and


Algorithms by Masood, Adnan ISBN 9781783558476,
1783558474

_____ Click the link below to download _____


https://ebooknice.com/product/learning-f-functional-
data-structures-and-algorithms-36703230

Explore and download more ebooks at ebooknice.com


Here are some recommended products that might interest you.
You can download now and explore!

(Ebook) Learning Functional Data Structures and Algorithms: Learn


functional data structures and algorithms for your applications and
bring their benefits to your work now by Atul S. Khot, Raju Kumar
Mishra ISBN 9781785888731, 1785888730
https://ebooknice.com/product/learning-functional-data-structures-and-
algorithms-learn-functional-data-structures-and-algorithms-for-your-
applications-and-bring-their-benefits-to-your-work-now-7196680
ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason; Viles, James


ISBN 9781459699816, 9781743365571, 9781925268492, 1459699815,
1743365578, 1925268497

https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Learning functional data structures and algorithms learn


functional data structures and algorithms for your applications and
bring their benefits to your work now by Khot, Atul S.;Mishra, Raju
Kumar ISBN 9781785885884, 9781785888731, 178588588X, 1785888730
https://ebooknice.com/product/learning-functional-data-structures-and-
algorithms-learn-functional-data-structures-and-algorithms-for-your-
applications-and-bring-their-benefits-to-your-work-now-11793580
ebooknice.com

(Ebook) Learning JavaScript Data Structures and Algorithms by Loiane


Groner ISBN 9781785285493, 1785285491

https://ebooknice.com/product/learning-javascript-data-structures-and-
algorithms-5847376

ebooknice.com
(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT II Success)
by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena Alfredsson, Hans


Heikne, Sanna Bodemyr ISBN 9789127456600, 9127456609

https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) Java Collections: An Introduction to Abstract Data Types, Data


Structures and Algorithms by David A. Watt, Deryck F. Brown ISBN
9780471899785, 047189978X

https://ebooknice.com/product/java-collections-an-introduction-to-
abstract-data-types-data-structures-and-algorithms-1824036

ebooknice.com

(Ebook) AI algorithms, data structures, and idioms in Prolog, Lisp,


and Java by George F. Luger, William A. Stubblefield ISBN
9780136070474, 0136070477

https://ebooknice.com/product/ai-algorithms-data-structures-and-
idioms-in-prolog-lisp-and-java-2419930

ebooknice.com

(Ebook) Data Structures & Algorithms in Go by Hemant Jain

https://ebooknice.com/product/data-structures-algorithms-in-go-6857714

ebooknice.com
Learning F Functional Data Structures and Algorithms
1st Edition Masood Digital Instant Download
Author(s): Masood, Adnan
ISBN(s): 9781783558476, 1783558474
Edition: 1
File Details: PDF, 4.25 MB
Year: 2015
Language: english
Learning F# Functional Data Structures
and Algorithms
Table of Contents
Learning F# Functional Data Structures and Algorithms
Credits
Foreword
Foreword
Foreword
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Embrace the Truth
Exploring the functional programming paradigm
Thinking functional – why functional programming matters
A historical primer of F#
The Hello World example
A brief F# language primer
Syntactical similarities and differences
Benefits of using F# over C#
Summary
2. Now Lazily Get Over It, Again
Setting up the IDE
Your first F# project
Talk is cheap, show me some code
To understand recursion, you must understand recursion
Memoization with Fibonacci
Towers of Hanoi
Sorting lazily
F# 4.0 – new features
Summary
3. What's in the Bag Anyway?
Exploring data structures in F#
Arrays
Lists
List comprehensions
Sequences
Tuples and records
Option types
Sets and maps
Discriminated unions
The active pattern
F# implementation of sorting algorithms
Algorithmic complexity and the Big-O notation
The bubble sort
Quicksort
The merge sort
Summary
4. Are We There Yet?
Diving deep into enumerations and sequences
Enumerating a CSV file
Query expressions
Creating sequences from collections
Usage considerations for sequences
Summary
5. Let's Stack Up
Let's build a stack
Stack with concurrency support
Testing the stack
Algorithm – parenthesis matching using stacks
Summary
6. See the Forest for the Trees
Tree as a data structure
The binary search tree
Navigating the tree
Abstract syntax trees
Summary
7. Jumping the Queue
Let's make a functional queue
The FSharpx.Collections library
The MailboxProcessor class in F#
Summary
8. Quick Boost with Graph
Graphs
Modeling graphs using F#
The shortest path algorithm
Finding the minimal path sum
Summary
9. Sets, Maps, and Vectors of Indirections
Sets and maps
Vectors
F# and the Intermediate Language
Summary
10. Where to Go Next?
References and further readings
F# language resources
Component design guidelines
Functional programming guides
F# for fun and profit
Data science with F#
Math and statistics programming with F#
Machine learning with F#
Books and interactive tutorials
Try F#
The F# programming wikibook
The F# workshop
The F# cheat sheet
Video tutorials
Community projects – development tools
Community projects – functional programming
Community projects – data science programming
Community projects – the GPU execution
General functional programming
Academic resources
Summary
Index
Learning F# Functional Data Structures
and Algorithms
Learning F# Functional Data Structures
and Algorithms
Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written permission
of the publisher, except in the case of brief quotations embedded in critical articles or
reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its
dealers and distributors will be held liable for any damages caused or alleged to be
caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: June 2015

Production reference: 1240615

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78355-847-6

www.packtpub.com
Credits
Author

Adnan Masood, Ph.D.

Reviewers

Steve Bearman

Taha Hachana

Marcin Juraszek

Rohit Pathak

Commissioning Editor

Kunal Parikh

Acquisition Editor

Shaon Basu

Content Development Editor

Rahul Nair

Technical Editor

Parag Topre

Copy Editors

Relin Hedly

Sonia Mathur

Project Coordinator

Nidhi Joshi
Proofreaders

Stephen Copestake

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Jason Monteiro

Production Coordinator

Nilesh R. Mohite

Cover Work

Nilesh R. Mohite
Foreword
Functional programming is about to become mainstream, and learning F# helps a
programmer build skills in multiple paradigms. It doesn't surprise me at all that Adnan
has found his way to functional programming. His dedication to technological
excellence is expressed eloquently in this book, and if you want to get started with F#,
this is the book to read.

Jon Flanders

Pluralsight Trainer, Microsoft MVP


Foreword
In the era of multiprocessor and multimachine processing, functional principles are
becoming increasingly important for modern programmers. For those developing in the
Microsoft ecosystem, F# is a functional first multiparadigm language that allows
practitioners to apply these principles in a truly powerful way. As developers become
more familiar with functional data structures and the algorithms that use them truly
safely, by extension, powerful software will become a more commonplace commodity
that will drive the next era of technological innovation. I can't think of a more thorough
and thoughtful person to help guide us through these principles than Adnan. Enjoy!

Seth Juarez

Senior Technical Evangelist, Microsoft


Foreword
F# is a functional and object-oriented programming language with the power of the
.NET Framework. This language has gained huge popularity among a broad range of
programmers. With a focus on writing simple code to solve complex problems, F# is
being used by data scientists, enterprise developers, and enterprise enthusiasts. In fact,
its popularity has increased so much in recent times that according to the TIOBE index
(ranked 11th as of March 2015), F# is all set to gain an esteemed position among the top
10 programming languages.

With the rise in interest and usage around F#, it's bound to continue to attract the
attention of hobbyists who want to try out writing programs with F#. I am very excited
about Adnan Masood's efforts and appreciative of his work, which focuses on the
basics of functional programming, data structures, and algorithms. Adnan has followed a
very structured approach to take you on a journey where you can discover and
familiarize yourself with this powerful multiparadigm programming language. Starting
with setting the context and discussing the basics of F# programming, Adnan gradually
moves on to a more detailed and increasingly focused conversation surrounding data
structures and algorithms. He also covers approaches related to testing bespoke data
structures and algorithms. Towards the end, Adnan covers the implementation of
modern and complex abstract data types (ADTs) and highlights how to use parallel
programming and asynchrony within the F# setting.

I highly recommend this book and ask you to focus your energies on learning this
amazing and powerful multiparadigm, open source, and cross-platform programming
language. This book will help you tackle computing problems with a simple,
maintainable, and robust code.

Happy F# Programming.

Hammad Rajjoub

Architect Advisor, Mobility Lead (Asia), Microsoft


About the Author
Adnan Masood, Ph.D. is a developer, software architect, and researcher and
specializes in machine learning and Bayesian belief networks. He is an avid engineer
and is most comfortable working with the IDE. Before joining Green Dot Corporation, a
leading prepaid financial technology institution, he enjoyed life as a principal engineer
of a start-up and worked for a leading UK nonprofit organization as a solutions
architect.

A strong believer in the development community, Adnan is an active member of the


Open Web Application Security Project (OWASP), an organization dedicated to
software security. In the .NET community, he is a cofounder and president of the
Pasadena .NET Developers group, which he has been successfully leading for 8 years.
He pursues interests in algorithmic puzzles, machine learning, functional programming,
cloud computing, service-oriented architecture (SOA), .NET, design patterns,
application security, and robotics. He has also led a number of successful enterprise
solutions and consulted for several Fortune 500 company projects.

Adnan devotes himself to his own continual, practical education. He holds certifications
in big data, machine learning, and systems architecture from Massachusetts Institute of
Technology; an Application Security certification from Stanford University; an SOA
Smarts certification from Carnegie Mellon University; and certifications as a
ScrumMaster, Microsoft Certified Trainer, Microsoft Certified Solutions Developer,
and Sun Certified Java Developer.

Adnan has taught Windows Communication Foundation (WCF) courses at the University
of California, San Diego, and loves to conduct presentations at top academic and
technology conferences (for example, IEEE-HST, IASA, and DevConnections), local
code camps, and user groups. He is also a volunteer FLL robotics coach for middle
school students at Universal Academy of Florida.

At home, his two very energetic boys, Zakariya and Ali, keep him busy—but not quite
busy enough to keep him from compulsively buying (though not always reading) books
in all formats. Adnan defines Pluto as a planet, chocolate as a food group, and A Game
of Thrones as historical fiction.

For more details, visit Adnan's blog (http://blog.adnanmasood.com), GitHub repository


(http://github.com/adnanmasood), and Twitter (@adnanmasood). Adnan can be reached
at <[email protected]>.
Acknowledgments
I am very grateful to the technical reviewers—Steve Bearman, Taha Hachana, Marcin
Juraszek, and Rohit Pathak—whose meticulous reviews proved invaluable in improving
the quality of this book. Thank you for your diligence and your help throughout the
process. Thanks to the excellent team at Packt Publishing. I would also like to thank the
technical editor, Parag Topre, and the content development editor, Rahul Nair, who
worked with me and kept this project on track to publish this book. Your assistance as
an editor and reviewer along with your comments were invaluable in ensuring that this
book was a comprehensive and reliable source of information on F# and functional
programming.

Thanks to Don Syme and Microsoft Research, without whom neither F# nor this book
would have been possible, and to the excellent F# community that provides plenty of
resources. It has been my privilege to work closely with Jeff Bergman (Google), who
got me started on F# and functional programming. I am forever grateful to Stephen
Soong, for his unwavering support and feedback, and David Lazar, who allowed me to
run seemingly crazy ideas by him. I am indebted to all my friends and colleagues,
including Nicolas Naaman, David Gullett, Calvin Park, Teresa Watkins, Raja Peer,
Dave Banta, Ajit Kumar, Dr. Jevdet Rexhepi, Paul Watson, Dr. John Dean, Kamran
Masood, Jim Java, Muhammad Mansoor, Antony Chhan, Rashid Kamran, Jeff Cox,
Mobeen Minai, Rob Walling, and Kamran Zameer, to name a few, for reading the early
drafts and providing feedback and encouragement. And last but not least, special thanks
to my family for their support and to my kids, Zakariya and Ali; without their
shenanigans, this book would have been finished 6 months earlier. Love you guys!
About the Reviewers
Steve Bearman is a software developer with his own software and consulting
company, Suzy B Studios. He supports all sectors from science and engineering through
business and finance and specializes in the thorny, complex problems where
architecture, algorithms, performance, and usability are critical. He has been
developing with .NET for over a decade. He has long been functionally oriented; one of
his first preferred programming languages, years ago, was the early functional,
mathematical programming language APL.

Steve has a special fondness for good algorithms and appropriate technology. He has
taught university graduate-level computer science and managed marketing and
operations as the VP of a manufacturing corporation. Steve has published technical
papers dealing with data, its analysis, interpretation, and automated collection. He
speaks frequently on technical topics. He has an SB in Mathematics from MIT and an
MA in applied mathematics, concentrating on algorithms and mathematical statistics,
from the University of California, San Diego.

He enjoys life with his beautiful wife and two dogs, holds black belts in two styles of
martial arts, juggles, rides his unicycle, and enjoys the arts and the outdoors.

Taha Hachana is an enthusiast F# hacker. He has been using this language since 2008
(2 years before it became a Microsoft product). As an active community member, he has
been maintaining several open source F# projects on GitHub, focusing on web
development with the WebSharper framework and data visualization. When he's not
coding, Taha enjoys practicing martial arts and yoga. You can follow him on Twitter at
@TahaHachana and read his blog at http://fsharp-code.blogspot.com/.

Marcin Juraszek is a software engineer at Microsoft. He is associated with Office


Online, a web browser-based version of the Microsoft Office productivity suite.

He holds bachelor's of engineering and master's of science degrees in computer science


from the Silesian University of Technology in Gliwice, Poland. Before moving to the
U.S., Marcin worked at Future Processing, one of the fastest growing software
companies in central and eastern Europe.

He has been a .NET developer since the last 4 years. His expertise spans across most of
.NET stack, including C#, VB.NET, F#, ASP.NET, XAML, WPF, Silverlight, LINQ,
and .NET Core. He's also interested in new technologies, such as TypeScript, Azure,
Roslyn, and so on.

He runs his own programming-oriented blog at http://marcinjuraszek.com and is an


active member of the Stack Overflow community.

Rohit Pathak has a degree in computer science from Rajiv Gandhi Technical
University. He picked up his interest in functional programming while working on High
Performance Computing (HPC) at AITR (Acropolis Institute of Technology and
Research). For years, he worked at Innovation at Incubation Labs and NTI (NEC
Technologies India Limited), focusing on machine learning, static model checking,
compilers, and HPC. Currently, he is working as a lead software engineer with the
system and verification group at Cadence Design Systems.
www.PacktPub.com
Support files, eBooks, discount offers,
and more
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and
ePub files available? You can upgrade to the eBook version at www.PacktPub.com and
as a print book customer, you are entitled to a discount on the eBook copy. Get in touch
with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up
for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.
Preface
"If there's a book that you want to read, but it hasn't been written yet, then you must write it."

-- Toni Morrison

F# is a multiparadigm programming language that encompasses object-oriented,


imperative, and functional programming language properties. The functional paradigm
can be defined as programming with pure functions, programming by function
composition, and a combination of both. For over a quarter of a century, functional
programming languages such as Lisp, Haskell, and standard ML existed in academia,
but industry adaption has been quite slow. With the introduction of F#, an open source
functional programming language, this trend is witnessing a significant change. F# runs
on the .NET runtime and supports libraries from other IL-based programming languages.

Due to the seemingly overarching title of this manuscript, a few disclaimers are in
order. This book is an introduction to F#, functional data structures, and algorithms.
These topics are fairly large in their individual capacity. A large body of growing
literature exists in each of these areas itself. Therefore, it won't be a reasonable
expectation to provide a comprehensive picture of data structures and algorithms in the
limited amount of space available in this book. Instead, this book is intended as a
cursory introduction to the use and development of data structures and algorithms using
F#. The goal is to provide a broader overview and resources to the reader to get started
with functional programming using F#.

This book is written with a few assumptions, keeping the reader in mind. We assume
that the reader has basic knowledge of an imperative programming language and object-
oriented concepts. Readers are highly encouraged to try out examples, use the resources
listed in Chapter 10, Where to Go Next?, and review specialized texts for a more
comprehensive treatment of algorithms and data structures.

Starting with the basic concepts of F#, this book will help you to solve complex
computing problems with simple, maintainable, and robust code. Using easy-to-
understand examples, you will learn how to design data structures and algorithms in F#
and apply these concepts in real-life projects, as well as gain insights into how to reuse
libraries available in community projects. You will also learn how to set up Visual
Studio .NET and F# compiler to work together, implement the Fibonacci sequence and
Tower of Hanoi using recursion, and apply lazy evaluation for quick sorts. The book
will then cover built-in data structures and take you through enumerations and
sequences. You will gain knowledge about stacks, graph-related algorithms, and
implementations of binary trees. Next, you will understand the custom functional
implementation of a queue and look at the already available collection and concurrent
collection structures. You will also review sets and maps and explore the
implementation of a vector.

In the final leg of this book, you will find resources and references that will give you a
great overview of how to build an application in F# and do great things. We have tried
our best to provide attribution to all the resources used in this book. However, if
anything has been missed, let us know. To build upon the fundamentals you would learn
in this book, we have created a code repository to solve project Euler algorithmic
problems. Project Euler is a series of challenging mathematical and computer
programming problems that require working with algorithms and data structures. You
will see our solutions on the GitHub repo at
https://github.com/adnanmasood/Euler.Polyglot.

In the cover, the choice of lush landscape and central figure reminiscent of general
Sherman trail is an attempt to portray the variety of programming paradigms and the
potential strength of functional concepts. In the words of Ryan Bozis, learn these
functional constructs, and you'll be able to program your very own forest. Being
polyglot is good! Learning a new programming language broadens your thinking and
provides you a competitive edge. Happy functional programming!
What this book covers
Chapter 1, Embrace the Truth, explains F#'s rather special role in the functional
programming world. You will also discuss F#'s roots in ML, the context in which F#
works, that is, running on top of .NET stack, compiled to IL, utilizing BCL and the
hybrid nature of the languages.

Chapter 2, Now Lazily Get Over It, Again, will prepare you to delve into the
intermediate F# concepts which you are going to utilize later. It will help you in setting
up the Visual Studio .NET and F# Compiler to work together along with the
environment and runtime, review how to run your F# programs in IDE and through
interactive REPL shell, implement the Fibonacci sequence and Tower of Hanoi using
recursion, and apply lazy evaluation for quick sort.

Chapter 3, What's in the Bag Anyway?, will provide insights about the built-in data
structures—array, list, set, and map, and will present their typical use cases.

Chapter 4, Are We There Yet?, delves into sequence expression (seq), implementation
of custom enumeration for purpose of sequence expression (that is, paging
functionality), and application of simple custom types using records, tuples.

Chapter 5, Let's Stack Up, will help you build a basic ADT of a stack using F#,
implement the fundamental operations, and proceed to make a concurrent version of a
stack. You will also learn how to do unit testing in C# for an F# program and implement
the same test method in F#.

Chapter 6, See the Forest for the Trees, will explain graph related algorithms, and
teach you the implementation of your own trees. You will also learn to tackle tree
searching and various other traversal techniques.

Chapter 7, Jumping the Queue, discusses the custom functional implementation of a


queue. You will then be introduced to the FSharpX open source collection of functional
data structures. Finally, you will explore the F# agent of MailboxProcessor, for creating
async work flows, throttling, and post-processing of the results of asynchronous calls as
an example usage of a queue.

Chapter 8, Quick Boost with Graph, will briefly discuss how a graph can be
implemented in a functional language, and why it is a rather difficult task to undertake.
You will then discover some commonly used graph implementations and explore one of
the most typical shortest path graph implementation, Dijkstra.

Chapter 9, Sets, Maps, and Vectors of Indirections, reviews sets and maps, and
explores a custom implementation of a vector. Additionally, you are going to discuss
Intermediate Language and how it works in the .NET ecosystem.

Chapter 10, Where to Go Next?, is a reference chapter in which you can acquaint
yourself with the detailed list of different resources around the functional eco-system,
and the F# programming language. You will also find various guides, source code and
links, which will assist you in getting additional information you will need to polish
your knowledge about F#.
What you need for this book
To get started with working on F#, you will need Visual Studio 2013. Also, you will
need Windows or Linux/MacOS with Mono to build the server, console and GUI
applications. Visual Studio 2013 Professional/Community Edition is preferred.
Who this book is for
If you have just started your adventure with F#, then this book will help you take the
right steps to become a successful F# programmer, thereby improving your current
development skills. Intermediate knowledge of imperative programming concepts and a
basic understanding of the algorithms and data structures in .NET environments using
the C# language and BCL (Base Class Library) would be helpful.
Conventions
In this book, you will find a number of text styles that distinguish between different
kinds of information. Here are some examples of these styles and an explanation of their
meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows: " You
can also use the #help;; directive to list other directives inside FSI."

A block of code is set as follows:


val cubeMe : x:int -> int
> > cubeMe 9;;
val it : int = 729

Any command-line input or output is written as follows:


square 10;;
^^^^^^
error FS0039: The value or constructor 'square' is not defined

New terms and important words are shown in bold. Words that you see on the screen,
for example, in menus or dialog boxes, appear in the text like this: "When this function
is executed in F# interactive, you can immediately see the results upon invocation as in
the following screenshot."
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this
book—what you liked or disliked. Reader feedback is important for us as it helps us
develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention


the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help
you to get the most from your purchase.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you have purchased. If you
purchased this book elsewhere, you can visit http://www.packtpub.com/support and
register to have the files e-mailed directly to you. The GitHub repository for the code
files are also available at https://github.com/adnanmasood/Learning-fsharp.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you could report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent versions of this book. If
you find any errata, please report them by visiting http://www.packtpub.com/submit-
errata, selecting your book, clicking on the Errata Submission Form link, and entering
the details of your errata. Once your errata are verified, your submission will be
accepted and the errata will be uploaded to our website or added to any list of existing
errata under the Errata section of that title.

To view the previously submitted errata, go to


https://www.packtpub.com/books/content/support and enter the name of the book in the
search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works in any form on the Internet, please provide
us with the location address or website name immediately so that we can pursue a
remedy.

Please contact us at <[email protected]> with a link to the suspected pirated


material.

We appreciate your help in protecting our authors and our ability to bring you valuable
content.
Questions
If you have a problem with any aspect of this book, you can contact us at
<[email protected]>, and we will do our best to address the problem.
Chapter 1. Embrace the Truth
"Object oriented programming makes code understandable by encapsulating moving parts. Functional
programming makes code understandable by minimizing moving parts."

-- Michael Feathers

The history of functional programming can be traced back to the Church and Rosser's
original work on Lambda Calculus in 1936 and yet, the concepts and implementation of
this important programming paradigm are somehow limited to academia while its
object-oriented and imperative counterpart dominates the industry. Good news is, this
trend is changing fast! With the functional paradigm support in modern programming
languages, such as Scala, Clojure, F#, Ruby, and to some extent, the omnipresent
JavaScript, the benefits of functional programming are being realized. The increased use
of some classical functional languages, such as OCaml, Erlang, Scheme, and Lisp in
high-concurrency environments has led to realization of the functional advantages of
brevity, terseness, scalability and performance.

In this chapter, we will cover everything that a hobbyist F# developer, who is just
starting his/her adventure in functional programming, needs to know in order to be able
to follow the discussion through rest of the book. We will begin with a short explanation
of F# language's rather special role in the functional programming world, and will
explain why it isn't strictly a functional programming language. Throughout the book,
and in this chapter particularly, we will address the historic sketches of functional
languages and their predecessors. We will discuss F# language's roots in ML, the
context in which F# works, that is, running on top of .NET stack, compiled to IL,
utilizing BCL, and the hybrid nature of the languages. You will see several new terms
used in this and the following chapters; these terms will have a cursory definition, but
will be elaborated on as we discuss these topics in detail during subsequent chapters.

By the end of this chapter, you will be familiar with a brief history of functional
programming. With comparative code examples, we will analyze code samples using
mutable, and immulatable data structures as well as imperative control flow syntax that
will allow you, the reader, to fully understand and embrace the hybrid nature of F#.

In this chapter, we will cover the following topics:


A brief overview of Functional Programming Paradigm
Thinking functional—why functional programming matters
The F# language primer
Benefits of functional programming and functional data structures
Code samples comparing imperative and functional styles
Exploring the functional programming
paradigm
There is no universally accepted definition of functional programming, and any attempt
to do so usually results in seemingly infinite stack overflow/Reddit comment threads,
flame-wars, and eventually hate-mail. The following are the most agreed upon attributes
of a functional programming language:
Functions are the first class citizens
Expressions are preferred over statements
Immutability is revered; structures and data are transformed
Functions are pure, that is, without side effects
Composability of functions to combine and chain output
Programming constructs such as recursion and pattern matching are frequently used
Non-strict evaluation is the default paradigm

Like its namesake, the functional programming paradigm uses pure functions, as in
mathematical functions, as its core construct. The précis of function as a programming
language construct stems from Alonzo Church and J. Barkley Rosser's work on lambda
calculus. As in mathematical functions, the imperative in function based programing is
to avoid state and mutation. Like mathematical functions, one should be able to invoke a
function multiple times with no side effects, that is, always get the same answers. This
style of programing has deep implementation consequences; a focus on immutable data
(and structures) leads to programs written in a declarative manner since data structure
cannot be a modified piecemeal.

A function is a static, a well-defined mapping from input values to output values.


Functions being the first class citizens is an often said but seldom understood concept.
A programming construct being first class means it may possess certain attributes, such
as:
It can be named or an identifier can be assigned to it
It can be passed in as an argument, and returned as a value
It can hold a value, can be chained, and concatenated

Pure functions offer referential transparency, that is, a function always returns the same
value when given the same inputs. Pure functions are not always feasible in real-world
scenarios such as when using persistent storage, randomization, performing I/O, and
generating unique identifiers. Technically speaking, a time function shouldn't exist in a
pure functional programming language. Therefore, pure functional languages such as
Haskell use the notion of IO Monads to solve this dogmatic conundrum. Luckily for us,
the hybrid (albeit more practical) languages such as F# are multi-paradigm and can get
around this restriction quite easily.
Thinking functional – why functional
programming matters
Maintainability is one of the key non-functional requirements when it comes to code
upkeep. Software complexity is a deterrent for feature additions, bug fixes, reusability,
and refactoring. A well-structured program is not only easy to maintain, but also easy to
debug and reuse. In Why Functional Programming Matters - Research topics in
functional programming, John Huges argues that modularity is key to effective software
maintainability, and modularity means more than mere code segmentation. Decomposing
a technology or business problem into smaller segments, and then integrating these
smaller problems to build a solution, promotes modular and reusable development
practices. Code must be usable before it is reusable; the higher order functions and non-
strict (lazy) evaluation of functional programming help build smaller, readable, easily
testable, and generic modules.

Functional programing provides abstraction but it is relatively different from the


hierarchical facet which we are used to seeing in the object oriented paradigm. In
contrast with the object oriented tenet of abstraction, functional abstraction hides how
the code executes, and provides a protected logical environment which supports
referential transparency, that is, programming without side effects. This lets the
developer focus on the results based on the statement provided. Functional code is a
declaration that describes the results that a developer is trying to achieve, instead of
focusing on the steps to get there.

Functional syntax tends to be less verbose and more terse than its imperative or object
oriented counterpart. The terseness keeps KLOC low and often results to the improved
developer productivity. In terms of productivity, since functional programming
promotes and encourages rapid prototyping, it benefits building and testing out proof of
concept implementations. This results in code that has more brevity, is more resilient to
change, and has fewer bugs.

Even though this is not strictly a feature of functional programming, several cross-
cutting concerns come standard along with most functional programming languages.
These include protected environments, pattern matching, tail-call optimization,
immutable data structures, and garbage collection.

If you have written multi-threaded code, you'd know that debugging the concurrency
issues in a multi-threaded environment is difficult to say the least. Arguably, one of the
best features of functional programming is thread safety through immutability. The
notion of concurrent collections in modern programming languages has its roots in
functional programming. The design and use of immutable data structures prevents the
process from running into race conditions and therefore does not present a need for
explicit locking, semaphores, and mutex programs. This also helps in parallelization,
one of the unrealized promises of functional programming.

In this book, we will discuss these and various other functional programming features in
detail, especially in context of F#. As a reader who is potentially familiar with either
object oriented or imperative programming, you will enjoy the use of fluent-interface
methods, lazy and partial evaluation, currying and memoization, and other unique and
interesting concepts that make your life as a developer more fulfilling, and easier too.
A historical primer of F#
With the advent of a multi-paradigm language with functional programming support such
as Lisp in 1958 by John McCarthy, the functional paradigm gained mainstream
exposure. Due to its multi-paradigm nature, there is a debate around Lisp being a pure
functional programming language. However, Scheme, one of the Lisp dialects which
didn't appear till 1975, tends to favor the functional style. The salient features of this
style includes use of tail recursion and continuations to express control flow.

Furthermore, various other functional languages were developed in academia, mostly in


the areas of mathematical sciences for theorem proving. ML (meta-language) by Robin
Milner et al of University of Edinburgh (early 1970s) is a prime example of a
programming language used to first implement the Hindley–Milner type inference
system. This simply typed polymorphic lambda calculus language was later adapted to
build StandardML, Caml, and OCaml, unifying functional, OOP, and imperative
programming paradigms. Haskell emerged in 1990 by Simon Jones et al as a purely
functional programming language. Haskell supports lazy evaluation, non-strict
semantics, and strong static typing. Haskell is named after the logician Haskell Curry.
Not surprisingly, Currying is the functional approach to deconstructing a tuple into
evaluating a sequence of functions. It allows us to deconstruct a function that takes
multiple arguments into an equivalent sequence of sub-functions that are evaluated, one
argument at a time. We will explore currying further in the book.

F#, a product of Don Syme, and Microsoft Research, surfaced in 2005 as a modern
multi-paradigm functional programming language. F# originates from ML and has been
influenced by OCaml, C#, Python, Haskell, Scala, and Erlang. F# Software Foundation
(FSSF) defines the language as follows:

"F# is a mature, open source, cross-platform, functional-first programming


language. It empowers users and organizations to tackle complex computing
problems with simple, maintainable and robust code."

With an open source compiler, library, and toolset, F# is a multi-paradigm language for
the .NET platform with support for multiple operating systems via Mono. It supports
functional, object oriented, imperative, and explorative programming paradigms.
Software developers who specialize in Microsoft platform and tools can easily learn to
take advantage of this new language's functional and object-oriented features. This
allows them to use their existing skills, find new productivity gains, and leverage new
programming design approaches that cannot be easily expressed in objects alone.

We will be the first to admit that functional programming can be scary for those
accustomed to the object oriented and imperative style of coding. While functional
programming can lead to some mind-bending coding, the fundamentals are quite
straightforward. If you find yourself lost in lambdas, rest assured that it takes everyone
some time to master these expressions. Even though the primary focus of this book is not
F# programming but rather data structures, we will start by introducing some of the F#
language tenets to help get the reader up-to-speed.

The syntactical terseness of a functional language like F# can have an adverse effect on
the reader; since functional programming is characterized by its concise coding style,
brevity, and explicit modeling, this can be hard for those familiar with the verbose
algorithmic style of OO and imperative languages. Rest assured, F# also offers a rich
set of object oriented features and its integration with other .NET languages such as
C#.NET and VB.NET is nearly seamless.
The Hello World example
No book is complete without some quintessential Hello World examples. So here it is:
printfn "Hello World";;

Yes, this is all you need. Notice the terseness, simplicity, and lack of clutter. Now let's
run this in the F# interactive environment. In order to run it, you would need to have ";;"
at the end of the statement. We will provide more details on this interactive environment
setup later in Chapter 2, Now Lazily Get Over It, Again.

This is the response that you see when you run the preceding line of code. It is a
minimal viable example; however these attributes of simplicity, terseness, and
simplification extend beyond HelloWorld samples as you will see.

Let's look at a simple function, square. You can write a function in F# as follows:
let square = fun n -> n * n

Or you can write it in a simpler syntax like the next one. Notice the first-class
citizenship in action here:
let square n = n * n

When this function is executed in F# interactive, you can immediately see the results
upon invocation as in the following screenshot:
Discovering Diverse Content Through
Random Scribd Documents
king no honour: for who doubts that he is able to inflict them? but,
on the other hand, it does him great honour to restrain his powers,
to save many from the wrath of others, and sacrifice no one to his
own.

XVIII. It is creditable to a man to keep within reasonable bounds in


his treatment of his slaves. Even in the case of a human chattel one
ought to consider, not how much one can torture him with impunity,
but how far such treatment is permitted by natural goodness and
justice, which prompts us to act kindly towards even prisoners of
war and slaves bought for a price (how much more towards free-
born, respectable gentlemen?), and not to treat them with scornful
brutality as human chattels, but as persons somewhat below
ourselves in station, who have been placed under our protection
rather than assigned to us as servants. Slaves are allowed to run
and take sanctuary at the statue of a god, though the laws allows a
slave to be ill-treated to any extent, there are nevertheless some
things which the common laws of life forbid us to do to a human
being. Who does not hate Vedius Pollio[10] more even than his own
slaves did, because he used to fatten his lampreys with human
blood, and ordered those who had offended him in any way to be
cast into his fish-pond, or rather snake-pond? That man deserved to
die a thousand deaths, both for throwing his slaves to be devoured
by the lampreys which he himself meant to eat, and for keeping
lampreys that he might feed them in such a fashion. Cruel masters
are pointed at with disgust in all parts of the city, and are hated and
loathed; the wrong-doings of kings are enacted on a wider theatre:
their shame and unpopularity endures for ages: yet how far better it
would have been never to have been born than to be numbered
among those who have been born to do their country harm!

XIX. Nothing can be imagined which is more becoming to a


sovereign than clemency, by whatever title and right he may be set
over his fellow citizens. The greater his power, the more beautiful
and admirable he will confess his clemency to be: for there is no
reason why power should do any harm, if only it be wielded in
accordance with the laws of nature. Nature herself has conceived
the idea of a king, as you may learn from various animals, and
especially from bees, among whom the king’s cell is the roomiest,
and is placed in the most central and safest part of the hive;
moreover, he does no work, but employs himself in keeping the
others up to their work. If the king be lost, the entire swarm
disperses: they never endure to have more than one king at a time,
and find out which is the better by making them fight with one
another: moreover the king is distinguished by his statelier
appearance, being both larger and more brilliantly coloured than the
other bees. The most remarkable distinction, however, is the
following: bees are very fierce, and for their size are the most
pugnacious of creatures, and leave their stings in the wounds which
they make, but the king himself has no sting: nature does not wish
him to be savage or to seek revenge at so dear a rate, and so has
deprived him of his weapon and disarmed his rage. She has offered
him as a pattern to great sovereigns: for she is wont to practise
herself in small matters, and to scatter abroad tiny models of the
hugest structures. We ought to be ashamed of not learning a lesson
in behaviour from these small creatures, for a man, who has so
much more power of doing harm than they, ought to show a
correspondingly greater amount of self-control. Would that human
beings were subject to the same law, and that their anger destroyed
itself together with its instrument, so that they could only inflict a
wound once, and would not make use of the strength of others to
carry out their hatreds: for their fury would soon grow faint if it
carried its own punishment with it, and could only give rein to its
violence at the risk of death. Even as it is, however, no one can
exercise it with safety, for he must needs feel as much fear as he
hopes to cause, he must watch every one’s movements, and even
when his enemies are not laying violent hands upon him he must
bear in mind that they are plotting to do so, and he cannot have a
single moment free from alarm. Would any one endure to live such a
life as this, when he might enjoy the privileges of his high station to
the general joy of all men, without injuring any one, and for that
very reason have no one to fear? for it is a mistake to suppose that
the king can be safe in a state where nothing is safe from the king:
he can only purchase a life without anxiety for himself by
guaranteeing the same for his subjects. He need not pile up lofty
citadels, escarp steep hills, cut away the sides of mountains, and
fence himself about with many lines of walls and towers: clemency
will render a king safe even upon an open plain. The one fortification
which cannot be stormed is the love of his countrymen. What can be
more glorious than a life which every one spontaneously and without
official pressure hopes may last long? to excite men’s fears, not their
hopes, if one’s health gives way a little? to know that no one holds
anything so dear that he would not be glad to give it in exchange for
the health of his sovereign? “O, may no evil befall him!” they would
cry: “he must live for his own sake, not only for ours: his constant
proofs of goodness have made him belong to the state instead of
the state belonging to him.” Who would dare to plot any danger to
such a king? Who would not rather, if he could, keep misfortune far
from one under whom justice, peace, decency, security and merit
flourish, under whom the state grows rich with an abundance of all
good things, and looks upon its ruler in the same spirit of adoration
and respect with which we should look upon the immortal gods, if
they allowed us to behold them as we behold him? Why! does not
that man come very close to the gods who acts in a god-like manner,
and who is beneficent, open-handed, and powerful for good? Your
aim and your pride ought to lie in being thought the best, as well as
the greatest of mankind.

XX. A prince generally inflicts punishment for one of two reasons: he


wishes either to assert his own rights or those of another. I will first
discuss the case in which he is personally concerned, for it is more
difficult for him to act with moderation when he acts under the
impulse of actual pain than when he merely does so for the sake of
the example. It is unnecessary in this place to remind him to be slow
to believe what he hears, to ferret out the truth, to show favour to
innocence, and to bear in mind that to prove it is as much the
business of the judge as that of the prisoner; for these
considerations are connected with justice, not with clemency: what
we are now encouraging him to do is not to lose control over his
feelings when he receives an unmistakeable injury, and to forego
punishing it if he possibly can do so with safety, if not, to moderate
the severity of the punishment, and to show himself far more
unwilling to forgive wrongs done to others than those done to
himself: for, just as the truly generous man is not he who gives away
what belongs to others, but he who deprives himself of what he
gives to another, so also I should not call a prince clement who
looked goodnaturedly upon a wrong done to someone else, but one
who is unmoved even by the sting of a personal injury, who
understands how magnanimous it is for one whose power is
unlimited to allow himself to be wronged, and that there is no more
noble spectacle than that of a sovereign who has received an injury
without avenging it.

XXI. Vengeance effects two purposes: it either affords compensation


to the person to whom the wrong was done, or it ensures him
against molestation for the future. A prince is too rich to need
compensation, and his power is too evident for him to require to
gain a reputation for power by causing any one to suffer. I mean,
when he is attacked and injured by his inferiors, for if he sees those
who once were his equals in a position of inferiority to himself he is
sufficiently avenged. A king may be killed by a slave, or a serpent, or
an arrow: but no one can be saved except by some one who is
greater than him whom he saves. He, therefore, who has the power
of giving and of taking away life ought to use such a great gift of
heaven in a spirited manner. Above all, if he once obtains this power
over those who he knows were once on a level with himself, he has
completed his revenge, and done all that he need to towards the
punishment of his adversary: for he who owes his life to another
must have lost it, and he who has been cast down from on high and
lies at his enemy’s feet with his kingdom and his life depending upon
the pleasure of another, adds to the glory of his preserver if he be
allowed to live, and increases his reputation much more by
remaining unhurt than if he were put out of the way. In the former
case he remains as an everlasting testimony to the valour of his
conqueror; whereas if led in the procession of a triumph he would
have soon passed out of sight.[11] If, however, his kingdom also may
be safely left in his hands and he himself replaced upon the throne
from which he has fallen, such a measure confers an immense
increase of lustre on him who scorned to take anything from a
conquered king beyond the glory of having conquered him. To do
this is to triumph even over one’s own victory, and to declare that
one has found nothing among the vanquished which it was worth
the victor’s while to take. As for his countrymen, strangers, and
persons of mean condition, he ought to treat them with all the less
severity because it costs so much less to overcome them. Some you
would be glad to spare, against some you would disdain to assert
your rights, and would forbear to touch them as you would to touch
little insects which defile your hands when you crush them: but in
the case of men upon whom all eyes are fixed, whether they be
spared or condemned, you should seize the opportunity of making
your clemency widely known.

XXII. Let us now pass on to the consideration of wrongs done to


others, in avenging which the law has aimed at three ends, which
the prince will do well to aim at also: they are, either that it may
correct him whom it punishes, or that his punishment may render
other men better, or that, by bad men being put out of the way, the
rest may live without fear. You will more easily correct the men
themselves by a slight punishment, for he who has some part of his
fortune remaining untouched will behave less recklessly; on the
other hand, no one cares about respectability after he has lost it: it
is a species of impunity to have nothing left for punishment to take
away. It is conducive, however, to good morals in a state, that
punishment should seldom be inflicted: for where there is a
multitude of sinners men become familiar with sin, shame is less felt
when shared with a number of fellow-criminals, and severe
sentences, if frequently pronounced, lose the influence which
constitutes their chief power as remedial measures. A good king
establishes a good standard of morals for his kingdom and drives
away vices if he is long-suffering with them, not that he should seem
to encourage them, but to be very unwilling and to suffer much
when he is forced to chastise them. Clemency in a sovereign even
makes men ashamed to do wrong: for punishment seems far more
grievous when inflicted by a merciful man.

XXIII. Besides this, you will find that sins which are frequently
punished are frequently committed. Your father sewed up more
parricides in sacks during five years, than we hear of in all previous
centuries. As long as the greatest of crimes remained without any
special law, children were much more timid about committing it. Our
wise ancestors, deeply skilled in human nature, preferred to pass
over this as being a wickedness too great for belief, and beyond the
audacity of the worst criminal, rather than teach men that it might
be done by appointing a penalty for doing it: parricides,
consequently, were unknown until a law was made against them,
and the penalty showed them the way to the crime. Filial affection
soon perished, for since that time we have seen more men punished
by the sack than by the cross. Where men are seldom punished
innocence becomes the rule, and is encouraged as a public benefit.
If a state thinks itself innocent, it will be innocent: it will be all the
more angry with those who corrupt the general simplicity of
manners if it sees that they are few in number. Believe me, it is a
dangerous thing to show a state how great a majority of bad men it
contains.

XXIV. A proposal was once made in the Senate to distinguish slaves


from free men by their dress: it was then discovered how dangerous
it would be for our slaves to be able to count our numbers. Be
assured that the same thing would be the case if no one’s offence is
pardoned: it will quickly be discovered how far the number of bad
men exceeds that of the good. Many executions are as disgraceful to
a sovereign as many funerals are to a physician: one who governs
less strictly is better obeyed. The human mind is naturally self-willed,
kicks against the goad, and sets its face against authority; it will
follow more readily than it can be led. As well-bred and high-spirited
horses are best managed with a loose rein, so mercy gives men’s
minds a spontaneous bias towards innocence, and the public think
that it is worth observing. Mercy, therefore, does more good than
severity.

XXV, Cruelty is far from being a human vice, and is unworthy of


man’s gentle mind: it is mere bestial madness to take pleasure in
blood and wounds, to cast off humanity and transform oneself into a
wild beast of the forest. Pray, Alexander, what is the difference
between your throwing Lysimachus into a lion’s den and tearing his
flesh with your own teeth? it is you that have the lion’s maw, and
the lion’s fierceness. How pleased you would be if you had claws
instead of nails, and jaws that were capable of devouring men! We
do not expect of you that your hand, the sure murderer of your best
friends, should restore health to any one; or that your proud spirit,
that inexhaustible source of evil to all nations, should be satisfied
with anything short of blood and slaughter: we rather call it mercy
that your friend should have a human being chosen to be his
butcher. The reason why cruelty is the most hateful of all vices is
that it goes first beyond the ordinary limits, and then beyond those
of humanity; that it devises new kinds of punishments, calls
ingenuity to aid it in inventing devices for varying and lengthening
men’s torture, and takes delight in their sufferings: this accursed
disease of the mind reaches its highest pitch of madness when
cruelty itself turns into pleasure, and the act of killing a man
becomes enjoyment. Such a ruler is soon cast down from his throne;
his life is attempted by poison one day and by the sword the next;
he is exposed to as many dangers as there are men to whom he is
dangerous, and he is sometimes destroyed by the plots of
individuals, and at others by a general insurrection. Whole
communities are not roused to action by unimportant outrages on
private persons; but cruelty which takes a wider range, and from
which no one is safe, becomes a mark for all men’s weapons. Very
small snakes escape our notice, and the whole country does not
combine to destroy them; but when one of them exceeds the usual
size and grows into a monster, when it poisons fountains with its
spittle, scorches herbage with its breath, and spreads ruin wherever
it crawls, we shoot at it with military engines. Trifling evils may cheat
us and elude our observation, but we gird up our loins to attack
great ones. One sick person does not so much as disquiet the house
in which he lies; but when frequent deaths show that a plague is
raging, there is a general outcry, men take to flight and shake their
fists angrily at the very gods themselves. If a fire breaks out under
one single roof, the family and the neighbours pour water upon it;
but a wide conflagration which has consumed many houses must be
smothered under the ruins of a whole quarter of a city.

XXVI. The cruelty even of private men has sometimes been


revenged by their slaves in spite of the certainty that they will be
crucified: whole kingdoms and nations when oppressed by tyrants or
threatened by them, have attempted their destruction. Sometimes
their own guards have risen in revolt, and have used against their
master all the deceit, disloyalty, and ferocity which they have learned
from him. What, indeed, can he expect from those whom he has
taught to be wicked? A bad man will not long be obedient, and will
not do only as much evil as he is ordered. But even if the tyrant may
be cruel with safety, how miserable his kingdom must be: it must
look like a city taken by storm, like some frightful scene of general
panic. Everywhere sorrow, anxiety, disorder; men dread even their
own pleasures; they cannot even dine with one another in safety
when they have to keep watch over their tongues even when in their
cups, nor can they safely attend the public shows when informers
are ready to find grounds for their impeachment in their behaviour
there. Although the spectacles be provided at an enormous expense,
with royal magnificence and with world-famous artists, yet who
cares for amusement when he is in prison? Ye gods! what a
miserable life it is to slaughter and to rage, to delight in the clanking
of chains, and to cut off one’s countrymen’s heads, to cause blood to
flow freely wherever one goes, to terrify people, and make them flee
away out of one’s sight! It is what would happen if bears or lions
were our masters, if serpents and all the most venomous creatures
were given power over us. Even these animals, devoid of reason as
they are, and accused by us of cruel ferocity, spare their own kind,
and wild beasts themselves respect their own likeness: but the fury
of tyrants does not even stop short at their own relations, and they
treat friends and strangers alike, only becoming more violent the
more they indulge their passions. By insensible degrees he proceeds
from the slaughter of individuals to the ruin of nations, and thinks it
a sign of power to set roofs on fire and to plough up the sites of
ancient cities: he considers it unworthy of an emperor to order only
one or two people to be put to death, and thinks that his cruelty is
unduly restrained if whole troops of wretches are not sent to
execution together. True happiness, on the other hand; consists in
saving many men’s lives, in calling them back from the very gates of
death, and in being so merciful as to deserve a civic crown.[12] No
decoration is more worthy or more becoming to a prince’s rank than
that crown “for saving the lives of fellow-citizens”: not trophies torn
from a vanquished enemy, not chariots wet with their savage
owner’s blood, not spoils captured in war. This power which saves
men’s lives by crowds and by nations, is godlike: the power of
extensive and indiscrimate massacre is the power of downfall and
conflagration.

[1] Nobilis.

[2] The text is corrupt. I have followed Gertz’s conjectural emendation,


mansuefactionis, but I believe that Lipsius is right in thinking that a great deal
more than one word has been lost here.

[3] Pace.

[4] Tutum.

[5] Gertz reads sexagesimum, his sixtieth year, which he calls “the not very
audacious conjecture of Wesseling,” and adds that he does so because of the
words at the beginning of chap. xi. and the authority of Dion Cassius. The ordinary
reading is quadragesimum, “his fortieth year,” and this is the date to which Cinna’s
conspiracy is referred to by Merivale, “History of the Romans under the Empire,”
vol. iv. ch, 37. “A plot,” he says, “was formed for his destruction, at the head of
which was Cornelius Cinna, described as a son of Faustus Sulla by a daughter of
the Great Pompeius.” The story of Cinna’s conspiracy is told by Seneca, de Clem, i,
9, and Dion iv. 14, foll. They agree in the main fact; but Seneca is our authority for
the details of the interview between Augustus and his enemy, while Dion has
doubtless invented his long conversation between the emperor and Livia. Seneca,
however, calls the conspirator Lucius, and places the event in the fortieth year of
Augustus (A.D. 731), the scene in Gaul: Dion, on the other, gives the names of
Gnaeus, and supposes the circumstances to have occured twenty-six years later,
and at Rome. It may be observed that a son of Faustus Sulla must have been at
least fifty at this latter date, nor do we know why he should bear the name of
Cinna, though an adoption is not impossible.

[6] See Shakespeare’s “Julius Caesar,” Act IV, Sc. 1.

[7] In allusion to the title of “Father of his country,” bestowed by the Senate upon
Augustus. See Merivale, ch. 33.

[8] This whole comparison, which reads so meaninglessly both in Latin and in
English, is borrowed from the eternal declamations of Plutarch and the Greek
philosophers about βασιλεῖς and τύραννοι. See Plutarch, Lives of Philopoemen and
Aratus, Plato, Gorgias and Politicus; Arnold, “Appendix to Thucydides,” vol. i., and
“Dictionary of Antiquities,” s.v.

[9] De lra, ii. 11.

[10] Vedius Pollio had a villa on the mountain now called Punta di Posilippo, which
projects into the sea between Naples and Puteoli, which he left to Augustus, and
which was afterwards possessed by the Emperor Trajan. He was a freedman by
birth, and remarkable for nothing except his riches and his cruelty. Cf. Dion
Cassius, liv. 23; Pliny, H. N. ix. 23; and Seneca, “On Anger,” iii. 40, 2.

[11] The conquered princes who were led through Rome in triumphs were as a
rule put to death when the procession was over.

[12] The “civic” crown of oak-leaves was bestowed on him who had saved the life
of a fellow-citizen in war. It was bestowed upon Augustus, and after him upon the
other emperors, as preservers of the state.
THE SECOND BOOK OF THE DIALOGUE OF L.
ANNAEUS
SENECA, ADDRESSED TO NERO CAESAR.
ON CLEMENCY.
I. I have been especially led to write about clemency, Nero Caesar,
by a saying of yours, which I remember having heard with
admiration and which I afterwards told to others: a noble saying,
showing a great mind and great gentleness, which suddenly burst
from you without premeditation, and was not meant to reach any
ears but your own, and which displayed the conflict which was
raging between your natural goodness and your imperial duties. Your
prefect Burrus, an excellent man who was born to be the servant of
such an emperor as you are, was about to order two brigands to be
executed, and was pressing you to write their names and the
grounds on which they were to be put to death: this had often been
put off, and he was insisting that it should then be done. When he
reluctantly produced the document and put it into your equally
reluctant hands, you exclaimed: “Would that I had never learned my
letters!” O what a speech, how worthy to be heard by all nations,
both those who dwell within the Roman Empire, those who enjoy a
debatable independence upon its borders, and those who either in
will or in deed fight against it! It is a speech which ought to be
spoken before a meeting of all mankind, whose words all kings and
princes ought to swear to obey: a speech worthy of the days of
human innocence, and worthy to bring back that golden age. Now in
truth we ought all to agree to love righteousness and goodness;
covetousness, which is the root of all evil, ought to be driven away,
piety and virtue, good faith and modesty ought to resume their
interrupted reign, and the vices which have so long and so
shamefully ruled us ought at last to give way to an age of happiness
and purity.

II. To a great extent, Caesar, we may hope and expect that this will
come to pass. Let your own goodness of heart be gradually spread
and diffused throughout the whole body of the empire, and all parts
of it will mould themselves into your likeness. Good health proceeds
from the head into all the members of the body: they are all either
brisk and erect, or languid and drooping, according as their guiding
spirit blooms or withers. Both Romans and allies will prove worthy of
this goodness of yours, and good morals will return to all the world:
your hands will everywhere find less to do. Allow me to dwell
somewhat upon this saying of yours, not because it is a pleasant
subject for your ears (indeed, this is not my way; I would rather
offend by telling the truth than curry favour by flattery). What, then,
is my reason? Besides wishing that you should be as familiar as
possible with your own good deeds and good words, in order that
what is now untutored impulse may grow into matured decision, I
remember that many great but odious sayings have become part of
human life and are familiar in men’s mouths, such as that celebrated
“Let them hate me, provided that they fear me,” which is like that
Greek verse, έμοῦ θανόντος γαῖα μιχθήτω πνρί, in which a man bids
the earth perish in flame after he is dead, and others of the like sort.
I know not how it is, but certainly human ingenuity seems to have
found it easier to find emphatic and ardent expression for monstrous
and cynical sentiments: I have never hitherto heard any spirited
saying from a good and gentle person. What, then, is the upshot of
all this? It is that, albeit seldom and against your will, and after
much hesitation, you sometimes nevertheless must write that which
made you hate your letters, but that you ought to do so with great
hesitation and after many postponements, even as you now do.

III. But lest the plausible word “mercy” should sometimes deceive us
and lead us into the opposite extreme, let us consider what mercy is,
what its qualities are, and within what limits it is confined.
Mercy is “a restraining of the mind from vengeance when it is in its
power to avenge itself,” or it is “gentleness shown by a powerful
man in fixing the punishment of a weaker one.” It is safer to have
more than one definition, since one may not include the whole
subject, and may, so to speak, lose its cause: mercy, therefore, may
likewise be termed a tendency towards mildness in inflicting
punishment. It is possible to discover certain inconsistencies in the
definition which comes nearer the truth than all the rest, which is to
call mercy “self-restraint, which remits some part of a fine which it
deserves to receive and which is due to it.” To this it will be objected
that no virtue ever gives any man less than his due. However, all
men understand mercy to consist in coming short of the penalty
which might with justice be inflicted.

IV. The unlearned think that its opposite is strictness: but no virtue is
the opposite of another virtue. What, then, is the opposite of mercy?
Cruelty: which is nothing more than obstinacy in exacting
punishments. “But,” say you, “some men do not exact punishments,
and nevertheless are cruel, such as those who kill the strangers
whom they meet, not in order to rob them, but for killing’s sake, and
men who are not satisfied with killing, but kill with savage tortures,
like the famous Busiris,[1] and Procrustes, and pirates who flog their
captives and burn them alive.” This appears to be cruelty: but as it is
not the result of vengeance (for it has received no wrong), and is
not excited by any offence (for no crime has preceded it), it does not
come within our definition, which was limited to “extravagance in
exacting the penalties of wrongdoing.” We may say that this is not
cruelty, but ferocity, which finds pleasure in savagery: or we may call
it madness; for madness is of various kinds, and there is no truer
madness than that which takes to slaughtering and mutilating
human beings. I shall, therefore, call those persons cruel who have a
reason for punishing but who punish without moderation, like
Phalaris, who is not said to have tortured innocent men, but to have
tortured criminals with inhuman and incredible barbarity. We may
avoid hairsplitting by defining cruelty to be “a tendency of the mind
towards harsh measures.” Mercy repels cruelty and bids it be far
from her: with strictness she is on terms of amity.

At this point it is useful to inquire into what pity is; for many praise it
as a virtue, and say that a good man is full of pity. This also is a
disease of the mind. Both of these stand close to mercy and to
strictness, and both ought to be avoided, lest under the name of
strictness we be led into cruelty, and under the name of mercy into
pity. It is less dangerous to make the latter mistake, but both lead us
equally far away from the truth.

V. Just as the gods are worshipped by religion, but are dishonoured


by superstition, so all good men will show mercy and mildness, but
will avoid pity, which is a vice incident to weak minds which cannot
endure the sight of another’s sufferings. It is, therefore, most
commonly found in the worst people; there are old women and
girls[2] who are affected by the tears of the greatest criminals, and
who, if they could, would let them out of prison. Pity considers a
man’s misfortunes and does not consider to what they are due:
mercy is combined with reason. I know that the doctrine of the
Stoics is unpopular among the ignorant as being excessively severe
and not at all likely to give kings and princes good advice; it is
blamed because it declares that the wise man knows not how to feel
pity or to grant pardon. These doctrines, if taken separately, are
indeed odious, for they appear to give men no hope of repairing
their mistakes but exact a penalty for every slip. If this were true,
how can it be true wisdom to bid us put off human feeling, and to
exclude us from mutual help, that surest haven of refuge against the
attacks of Fortune? But no school of philosophy is more gentle and
benignant, none is more full of love towards man or more anxious to
promote the happiness of all, seeing that its maxims are, to be of
service and assistance to others, and to consult the interests of each
and all, not of itself alone. Pity is a disorder of the mind caused by
the sight of other men’s miseries, or it is a sadness caused by the
evils with which it believes others to be undeservedly afflicted: but
the wise man cannot be affected by any disorder: his mind is calm,
and nothing can possibly happen to ruffle it. Moreover, nothing
becomes a man more than magnanimity: but magnanimity cannot
coexist with sorrow. Sorrow overwhelms men’s minds, casts them
down, contracts them: now this cannot happen to the wise man
even in his greatest misfortunes, but he will beat back the rage of
Fortune and triumph over it: he will always retain the same calm,
undisturbed expression of countenance, which he never could do
were he accessible to sorrow.

VI. Add to this, that the wise man provides for the future and always
has a distinct plan of action ready: yet nothing clear and true can
flow from a disturbed source. Sorrow is awkward at reviewing the
position of affairs, at devising useful expedients, avoiding dangerous
courses, and weighing the merits of fair and just ones: therefore the
wise man will not feel pity, because this cannot happen to a man
unless his mind is disturbed. He will do willingly and highmindedly all
that those who feel pity are wont to do; he will dry the tears of
others, but will not mingle his own with them; he will stretch out his
hand to the shipwrecked mariner, will offer hospitality to the exile,
and alms to the needy—not in the offensive way in which most of
those who wish to be thought tender-hearted fling their bounty to
those whom they assist and shrink from their touch, but as one man
would give another something out of the common stock—he will
restore children to their weeping mothers, will loose the chains of
the captive, release the gladiator from his bondage, and even bury
the carcase of the criminal, but he will perform all this with a calm
mind and unaltered expression of countenance. Thus the wise man
will not pity men, but will help them and be of service to them,
seeing that he is born to be a help to all men and a public benefit, of
which he will bestow a share upon every one. He will even grant a
proportional part of his bounty to those sufferers who deserve blame
and correction; but he will much more willingly help those whose
troubles and adversities are caused by misfortune. Whenever he is
able he will interpose between Fortune and her victims: for what
better employment can he find for his wealth or his strength than in
setting up again what chance has overthrown? He will not show or
feel any disgust at a man’s having withered legs, or a flabby
wrinkled skin, or supporting his aged body upon a staff; but he will
do good to those who deserve it, and will, like a god, look
benignantly upon all who are in trouble. Pity borders upon misery: it
is partly composed of it and partly derived from it. You know that
eyes must be weak, if they fill with rheum at the sight of another’s
blearedness, just as it is not real merriment but hysteria which
makes people laugh because others laugh, and yawn whenever
others open their jaws: pity is a defect in the mind of people who
are extraordinarily affected by suffering, and he who requires a wise
man to exhibit it is not far from requiring him to lament and groan
when strangers are buried.

VII. But why should he not pardon?[3] Let us decide by exact


definition this other slippery matter, the true nature of pardon, and
we shall then perceive that the wise man ought not to grant it.
Pardon is the remitting of a deserved punishment. The reasons why
the wise man ought not to grant this remission are given at length
by those of whom this question is specially asked: I will briefly say,
as though it were no concern of mine to decide this point, “A man
grants pardon to one whom he ought to punish: now the wise man
does nothing which he ought not to do, and omits to [do] nothing
which he ought to do: he does not, therefore, remit any punishment
which he ought to exact. But the wise man will bestow upon you in a
more honourable way that which you wish to obtain by pardon, for
he will make allowances for you, will consult your interests, and will
correct your bad habits: he will act just as though he were
pardoning you, but nevertheless he will not pardon you, because he
who pardons admits that in so doing he has neglected a part of his
duty. He will only punish some people by reprimanding them, and
will inflict no further penalty if he considers that they are of an age
which admits of reformation: some people who are undeniably
implicated in an odious charge he will acquit, because they were
deceived into committing, or were not sober when they committed
the offence with which they are charged: he will let his enemies
depart unharmed, sometimes even with words of commendation, if
they have taken up arms to defend their honour, their covenants
with others, their freedom, or on any other honourable ground. All
these doings come under the head of mercy, not of pardon. Mercy is
free to come to what decision it pleases: she gives her decision, not
under any statute, but according to equity and goodness: she may
acquit the defendant, or impose what damages she pleases. She
does not do any of these things as though she were doing less than
justice requires, but as though the justest possible course were that
which she adopts. On the other hand, to pardon is not to punish a
man whom you have decided ought to be punished; pardon is the
remission of a punishment which ought to be inflicted. The first
advantage which mercy has over it is that she does not tell those
whom she lets off that they ought to have suffered: she is more
complete, more honourable than pardon.”

In my opinion, this is a mere dispute about words, and we are


agreed about the thing itself. The wise man will remit many
penalties, and will save many who are wicked, but whose
wickedness is not incurable. He will act like good husbandmen, who
do not cultivate only straight and tall trees, but also apply props to
straighten those which have been rendered crooked by various
causes; they trim some, lest the luxuriance of their boughs should
hinder their upward growth, they nurse those which have been
weakened by being planted in an unsuitable position, and they give
air to those which are overshadowed by the foliage of others. The
wise man will see the several treatments suitable to several
dispositions, and how what is crooked may be straightened. . . .

[1] A king of Egypt, who sacrificed strangers, and was himself slain by Hercules.

[2] “Three or four wenches where I stood, cried ‘Alas, good soul!—’ and forgave
him with all their hearts: but there’s no heed to be taken of them; if Caesar had
stabbed their mothers, they would have done no less.”—“Julius Caesar,” act i. sc.
2.

[3] See above, chap. v.


THE END.
INDEX.
A

Alexander the Great, 78, 98, 135, 141, 411.

Alexandria, Library of, 270.

Anger, 48; signs of, 49; results of, 50; definitions of, 50n; animals
not subject to, 52; not natural, 54; should be resisted at the
beginning, 57; examples of its results, 60; not necessary against
enemies, 60; nor useful, 63; not necessary for punishment, 68;
contrasted with reason, 69; creates vain-glory, but not
magnanimity, 73; cannot act without the approval of the mind, 77;
contrasted with ferocity, 80; the wise man will never be angry, 81;
anger and fear, 87; anger ought to be done away with, 88; must
never become a habit, 90; remedies for, 93; some men more
prone to, than others, 93; influence of education, 95; and of
prosperity, 96; cause of, 97; effect of trifles, 99; delay the best
remedy, 104; anger caused by ignorance or arrogance, 106; or by
desire for revenge, 108; its hideousness and danger, 111; its
power, 114; contrasted with other vices and passions, 116; how to
avoid it, 120; examples of anger indulged in, Cambyses, 131, 139;
Astyages, 133; Darius, 135; Xerxes, 135; Alexander, 135;
Lysimachus, 136; Caligula, 137, 139; Rhinocolura, 138; Cyrus,
139; examples of anger controlled, Antigonus, 140; Philip, 141;
Augustus, 142; how injuries ought to be bourne, 144; better to
heal than to avenge them, 146; the evils of anger, 147; its trifling
beginnings, 149; money, 151; other causes, 152; value of self-
examination, 154; how to soothe the anger of others, 156;
Augustus and Vedius, 158; anger should be got rid of altogether,
159.
Animals, anger in, 49, 52.

Antigonus (monophthalmus), 141.

Antisthenes, 45.

Antonius, M., 374, 391.

Aristides, 341.

Aristotle, 51n, 52, 58, 68, 118, 135, 287, 288.

Apicius, the glutton, 217, 336.

Asinius Pollio, 142, 285.

Astyages, King of Persia, 133.

Augustus. See Caesar.

Avarice, conquered by anger, 114.

Athenodorus, quoted, 259, 265.

Bees, 405.

Bibulus, L., 181.

Bion, quoted, 267, 282.

Books, should be bought to read, not for show, 270.

Brutus, L. Junius, 183.

Brutus, M. Junius, 330.

Burrus, prefect of Nero, 415.


C

Caelius (Antipater), 125.

Caesar, Augustus, 142, 158, 165, 182, 293, 372, 391, 393, 401.

Caesar, Claudius, 360, 369, 370.

Caesar, Gaius (Caligula), 44, 74, 109, 137, 140, 276, 280, 316, 334,
376.

Caesar, Gaius, grandson of Augustus, 373.

Caesar, Gaius Julius, 98, 149, 181, 333.

Caesar, Germanicus, brother of Claudius, 374.

Caesar, Lucius, grandson of Augustus, 373.

Caesar, Nero, 382, 396, 415.

Caesar, Tiberius, 11, 182, 373.

Caligula. See Caesar, Gaius.

Calmness, a sign of wisdom, 27.

Cambyses, 131, 139.

Cato, M., 5, 7, 10, 23, 31, 40, 108, 156, 192, 196, 228, 285, 286,
341.

Chaerea, 44.

Chrysippus, 242, 247, 248, 252.

Cicero, 192, 274, 295.

Cimber, Tillius, 149.


Cinna, L., 392.

Claudius Caudex, 307,

Cleanthes, 247, 252.

Clemency, 380; becomes no one more than a king, 384, 386;


clemency of Augustus, 391; and of Nero, 396; distinguishes
between kings and tyrants, 397; makes a king beloved, 399;
Tarius, 401; clemency towards slaves, 404; the king-bee, 405;
clemency in inflicting punishment, 407; makes men ashamed to
do wrong, 410; clemency of Nero, 415; definitions of Mercy, 417;
of cruelty, 417; of pity, 418; of pardon, 421.

Clitus, killed by Alexander, 135.

Cloelia, 183.

Comfort, excess of, 13.

Consolation, 162, 320, 353.

Contempt, 36.

Cordus, A. Cremutius, 162, 196, 197.

Cornelia, wife of L. Drusus, 183.

Cornelia, mother of the Gracchi, 183, 345.

Corvinus, M. Valerius, 307.

Cotta, C. Aurelius, 345.

Courage, aims high, 18; born of desperation, 398.

Cruelty, caused by anger, 80; cannot be left off, if once begun, 399;
inhumanity of, 411; shown in kings, 411; and in private men, 412;
the opposite of mercy, 417.

Cyrus (the elder), 139.

Darius, 135.

Death, quickness of, 21; not an evil, 23; a release from pain, 190.
191.

Delay, a remedy for anger, 104, 115, 129; and for grief, 172.

Demetrius the Cynic, quoted, 7, 16.

Demetrius Poliorcetes, 28.

Demochares (Parrhesiastes), 141 142.

Democritus, 18, 85, 122, 255, 278.

Dentatus, Curius, 264, 307.

Desperation, breeds courage, 398.

Diodorus, the Epicurean, 255.

Diogenes, the Cynic, 225, 267, 268,

Diogenes, the Stoic, 156,

Dionysius, of Syracuse, 186, 397,

Drusilla, 376.

Drusus, Livius, 183, 295.

Drusus, N. Claudius, senior, 373.


Drusus, N. Claudius, 166, 169.

Duillius, C. 307.

Education, should be carefully regulated, 95.

Epicurus, and Epicureans, 41, 42, 218, 219, 242, 248.

Exile, 325.

Fabianus (Papirius), quoted, 302, 309.

Fabius (Cunctator), 61, 106.

Fabricius, 7, 8.

Fear, felt by those who inspire it, 87; in moderation restrains men,
398.

Ferocity, contrasted with anger, 80; and with cruelty, 418.

Firmness, the, of a wise man, 22, sqq.

Friendship, 265.

Good, the highest, definition of, 208. 212, 215, 221, 244.

Gracchi, the, 183, 345.

Grief, examples of, 165; extreme grief unnatural, 171; cured by time,
172; counterfeited, 282; should be countered by reason, 346; its
unprofitableness, 357; cannot co-exist with magnanimity, 419.
H

Hannibal, 61, 78, 80.

Happiness, 204; how to gain it, 206; definitions of, 208; in


connexion with pleasure, 211; consists in virtue, 222; excess
makes men greedy, 382.

Harpagus, 133.

Heraclitus, 85.

Hieronymus, quoted, 71.

Hippias, 98.

Injury, cannot touch a wise man, 25, 32, 41, 42; distinguished from
insult, 27, 35; can be endured, 144.

Insult, distinguished from injury, 27, 35; how received by Diogenes


and Cato, 156.

Irascibility, contrasted with anger, 53, 71.

Julia Augusta (title of Livia), 168.

Kanus, Julius, 280, 281.

Laberius, quoted, 87.


Lacedaemonians, the, 13.

Leisure, advantages of, 240, sqq.

Life, shortness of, 160, 161, 175, 193, 288; its misery, 175; three
kinds of, 248; divided into three parts, 302.

Livia, wife of Augustus (afterwards Julia Augusta), 165, 168, 392.

Livius, T., quoted, 74, 270.

Love, conquered by anger, 114.

Lucretia. 183.

Lucretius, quoted, 258.

Luxury, 218, 306.

Lysimachus, 136, 411.

Maecenas, 9.

Magnanimity, repels insult, 36; not caused by anger, 73, 122; does
not feel blows, 144; befits all men, 387; cannot co-exist with
sorrow, 419.

Marcellus, M. Claudius, 332.

Marcellus, M. Claudius, son of Octavia, 165, 373.

Mercy, inclines men to innocence, 411; definitions of, 417;


distinguished from pardon, 422.

Metellus, L. Caecilius, 309.


Mindyrides, the Sybarite, 99.

Misfortunes, how regarded by the wise man, 3; are to the advantage


of those to whom they happen, 6; are the test of brave men, 11,
12, 17; generally come unexpectedly, 173; attack all alike, 178;
alleviated by habit, 271, 322.

Money, evils of, 151. See Riches.

Mucius, 7.

Nero. See Caesar.

Nomentanus, 217.

Octavia, sister of Augustus, 165, 372.

Oeobazus, 135.

Ovid, quoted, 18, 52, 84, 228.

Pardon, definition of, 421.

Pastor, 109.

Paulus, L. Aemilius, 180.

Peace of mind, definition of, 122, 255; how to attain it, etc., 255,
sqq.

Peripatetics, the, 50n.


Phaethon, 18.

Phalaris, 418.

Philip, of Macedon, 141, 142.

Philip, physician of Alexander, 98

Pisistratus, 128.

Piso, Gnaeus, 70.

Pity, definition of, 418, 419; borders on misery, 421.

Plato, 55, 72, 95, 97, 129, 198 286.

Pleasure, has no connexion with virtue, 211, 212; belongs to good


and bad alike, 213; not the aim of virtue, 214; pleasures of bad
men, 216; and of the wise, 217; the Epicurean doctrine, 218; all
pleasure is short-lived, 365.

Pollio, Asinius, 142, 285.

Pollio, Vedius, 158, 402.

Pompeius, 78n, 98, 150, 181, 192, 276, 308.

Pompeius, Sextus, 372.

Posidonius, his definition of anger, 50n.

Poverty, 333; no inconvenience to an exile, 337.

Praexaspes, 131.

Predestination, 194.

Property, 267. See Riches.


Prosperity, 4, 10; fosters anger, 96.

Providence, 1, sqq.

Publilius, quoted, 275.

Pulvillus, 179.

Punishment, why inflicted, 407; should not be frequent, 410.

Pythagoras, 126.

Pythias, 135.

Rage, does not befit kings, 317.

Reason, only strong apart from the passions, 56; its power, 69;
contrasted with anger, 70; cannot overcome some habits, 80.

Regulus, 7, 9, 339.

Relaxation, necessity for, 285.

Revenge, a cause of anger, 108, 146; has two effects, 408.

Rhinocolura, why so called, 138.

Riches, how regarded by the wise man, 229; and by the fool, 235;
better never to possess, than to lose, 267.

Rutilia, mother of C. Cotta, 345.

Rutilius, 7, 8, 196.

Scipio Africanus, 61, 371.


Scipio Africanus Minor, 61, 180, 285, 339, 372.

Sejanus, 162, 182, 196, 197, 276.

Self-examination, value of, 154, 206, 264.

Self-love, 106.

Sextius, Q., a Stoic, 113, 154.

Socrates, 7, 9, 31, 45, 65, 128, 130, 196, 234, 236, 238, 262, 285,
341.

Sorrow. See Grief.

Stilbo, 28.

Stoics and Stoicism, 22, 23, 41, 42, 50n, 94, 207, 218, 241, 242,
248, 419.

Sulkiness, a form of irascibility, 53.

Sulla, L., 8, 73, 78, 110, 179, 309, 397.

Suspicion, a cause of anger, 99.

Tarius, 401.

Telesphorus, the Rhodian, 136.

Theodorus, (Cyrenaicus), 279.

Theophrastus, quoted, 62, 64.

Thrift, advantage of, 269.

Tillius Cimber, 149.

You might also like