Get (Ebook) Learning F# Functional Data Structures and Algorithms by Masood, Adnan ISBN 9781783558476, 1783558474 free all chapters
Get (Ebook) Learning F# Functional Data Structures and Algorithms by Masood, Adnan ISBN 9781783558476, 1783558474 free all chapters
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
ebooknice.com
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
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312
ebooknice.com
https://ebooknice.com/product/java-collections-an-introduction-to-
abstract-data-types-data-structures-and-algorithms-1824036
ebooknice.com
https://ebooknice.com/product/ai-algorithms-data-structures-and-
idioms-in-prolog-lisp-and-java-2419930
ebooknice.com
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.
Livery Place
35 Livery Street
ISBN 978-1-78355-847-6
www.packtpub.com
Credits
Author
Reviewers
Steve Bearman
Taha Hachana
Marcin Juraszek
Rohit Pathak
Commissioning Editor
Kunal Parikh
Acquisition Editor
Shaon Basu
Rahul Nair
Technical Editor
Parag Topre
Copy Editors
Relin Hedly
Sonia Mathur
Project Coordinator
Nidhi Joshi
Proofreaders
Stephen Copestake
Safis Editing
Indexer
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
Seth Juarez
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
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.
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/.
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.
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
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 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."
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.
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.
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#.
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.
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 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.
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:
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.
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.
[1] Nobilis.
[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.
[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.
[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.
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.
[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.
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.
Antisthenes, 45.
Aristides, 341.
Bees, 405.
Caesar, Augustus, 142, 158, 165, 182, 293, 372, 391, 393, 401.
Caesar, Gaius (Caligula), 44, 74, 109, 137, 140, 276, 280, 316, 334,
376.
Cato, M., 5, 7, 10, 23, 31, 40, 108, 156, 192, 196, 228, 285, 286,
341.
Chaerea, 44.
Cloelia, 183.
Contempt, 36.
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.
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.
Drusilla, 376.
Duillius, C. 307.
Exile, 325.
Fabricius, 7, 8.
Fear, felt by those who inspire it, 87; in moderation restrains men,
398.
Friendship, 265.
Good, the highest, definition of, 208. 212, 215, 221, 244.
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
Harpagus, 133.
Heraclitus, 85.
Hippias, 98.
Injury, cannot touch a wise man, 25, 32, 41, 42; distinguished from
insult, 27, 35; can be endured, 144.
Life, shortness of, 160, 161, 175, 193, 288; its misery, 175; three
kinds of, 248; divided into three parts, 302.
Lucretia. 183.
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.
Mucius, 7.
Nomentanus, 217.
Oeobazus, 135.
Pastor, 109.
Peace of mind, definition of, 122, 255; how to attain it, etc., 255,
sqq.
Phalaris, 418.
Pisistratus, 128.
Praexaspes, 131.
Predestination, 194.
Providence, 1, sqq.
Pulvillus, 179.
Pythagoras, 126.
Pythias, 135.
Reason, only strong apart from the passions, 56; its power, 69;
contrasted with anger, 70; cannot overcome some habits, 80.
Regulus, 7, 9, 339.
Riches, how regarded by the wise man, 229; and by the fool, 235;
better never to possess, than to lose, 267.
Rutilius, 7, 8, 196.
Self-love, 106.
Socrates, 7, 9, 31, 45, 65, 128, 130, 196, 234, 236, 238, 262, 285,
341.
Stilbo, 28.
Stoics and Stoicism, 22, 23, 41, 42, 50n, 94, 207, 218, 241, 242,
248, 419.
Tarius, 401.