Complete Download (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 PDF All Chapters
Complete Download (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 PDF All Chapters
com
DOWLOAD EBOOK
ebooknice.com
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
https://ebooknice.com/product/learning-f-functional-data-structures-
and-algorithms-36703230
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
ebooknice.com
ebooknice.com
ebooknice.com
https://ebooknice.com/product/learning-javascript-data-structures-and-
algorithms-5847376
ebooknice.com
Learning Functional Data
Structures and Algorithms
Table of Contents
Learning Functional Data Structures and Algorithms
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
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
Downloading the color images of this book
Errata
Piracy
Questions
1. Why Functional Programming?
The imperative way
Higher level of abstraction
Functional programming is declarative
No boilerplate
Higher order functions
Eschewing null checks
Controlling state changes
Recursion aids immutability
Copy-on-write
Laziness and deferred execution
Composing functions
Summary
2. Building Blocks
The Big O notation
Space/time trade-off
A word frequency counter
Matching string subsets
Referential transparency
Vectors versus lists
Updating an element
Not enough nodes
Complexities and collections
The sliding window
Maps
Persistent stacks
Persistent FIFO queues
Sets
Sorted set
Summary
3. Lists
First steps
List head and tail
Drop elements
Concatenating lists
Persistent data structures
Tail call optimization
List append
List prepend
Getting value at index
Modifying a list value
Summary
4. Binary Trees
Node definitions
Building the tree
Size and depth
Complete binary trees
Comparing trees
Flipping a binary tree
Binary tree traversal
The accumulator idiom
Binary Search Trees
Node insertion
Searching a key
Updating a value
Exercising it
Summary
5. More List Algorithms
Binary numbers
Addition
Multiplication
Greedy algorithms and backtracking
An example of a greedy algorithm
The backtracking jig
Summary
6. Graph Algorithms
Reversing a list
Graph algorithms
Graph traversal
Avoiding list appending
Topological sorting
Cycle detection
Printing the cycle
Summary
7. Random Access Lists
Incrementing a binary number
Adding two binary numbers
List of tree roots
Insertion
Lookup
Removal, head, and tail
Update
Summary
8. Queues
Understanding FIFO queues
Functional FIFO queues
Invariants
Implementing a priority queue
Understanding priority queues/heaps
Leftist trees
Functional heaps
Summary
9. Streams, Laziness, and Algorithms
Program evaluation
Eager evaluation
Argument evaluation
Lazy evaluation
Lazy evaluation in Scala
Lazy evaluation in Clojure
Memoization - remembering past results
Memoization in Scala
Memoization in Clojure
Memoizing simpleFactFun
Streams
Stream in Scala
Indexing the elements of a stream
Creation of an infinite length stream
Stream is immutable
Creating a stream from another
Stream to list
Appending one stream to another
Length of a stream
Some mathematical functions of the stream class
Some more methods of the stream class
Streams (lazy sequence) in Clojure
Creating a memoized function of lazy sequences in Clojure
Some algorithms on stream
Arithmetic progression
Arithmetic progression in Scala
Arithmetic progression in Clojure
Standard Brownian motion
Standard Brownian motion in Scala
Standard Brownian motion in Clojure
Fibonacci series
First form of Fibonacci series
Second form of Fibonacci series
Fibonacci series in Scala
Fibonacci series in Clojure
Summary
10. Being Lazy - Queues and Deques
Imperative implementations
Amortization
Problem with queues
Strict versus lazy
Streams
Streams meet queues
A sense of balance
Amortized deques
Summary
11. Red-Black Trees
Terminology
Almost balanced trees
The concept of rotation
Red-Black trees
Inserting a node
The Black-Red-Red path
Left, left - red child and grand child
Left child, right grand child
Right child, right grand child
Right, left
Verifying the transformation
Complexity
Summary
12. Binomial Heaps
Binomial trees
Left child, right sibling
A binomial heap
Linking up
Inserting a value
Binary number equivalence
Merging
Find the minimum
Deleting the minimum
Exercising the code
Complexity
Summary
13. Sorting
Stable and unstable sorting
Stable sorting
Unstable sorting
Bubble sort
Scala implementation of bubble sort
Complexity of bubble sort
Selection sort
Complexity of selection sort
Insertion sort
Complexity of insertion sort
Merge sort
Splitting the sequence
Merging two sorted subsequences
Complexity of merge sort
Quick sort
Partition
Complexity of quick sort
Summary
Learning Functional Data
Structures and Algorithms
Learning Functional Data
Structures and Algorithms
Copyright © 2017 Packt Publishing
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 authors, 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.
Livery Place
35 Livery Street
ISBN 978-1-78588-873-1
www.packtpub.com
Credits
Authors
Copy Editor
Atul S. Khot
Gladson Monteiro
Raju Kumar Mishra
Raju Kumar Mishra is a consultant and corporate trainer for big data
and programming. After completing his B.Tech from Indian Institute of
Technology (ISM) Dhanbad, he worked for Tata Steel. His deep passion
for mathematics, data science, and programming took him to Indian
Institute of Science (IISc). After graduating from IISc in computational
science, he worked for Oracle as a performance engineer and software
developer. He is an Oracle-certified associate for Java 7. He is a
Hortonworks-certified Apache Hadoop Java developer, and holds a
Developer Certification for Apache Spark (O'Reilly School of
Technology and Databriks), and Revolution R Enterprise-certified
Specialist Certifications. Apart from this, he has also cleared Financial
Risk Manager (FRM I) exam. His interest in mathematics helped him in
clearing the CT3 (Actuarial Science) exam.
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 service@packtpub.com for more details.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full
access to all Packt books and video courses, as well as industry-leading
tools to help you plan your personal development and advance your
career.
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
Customer Feedback
Thank you for purchasing this Packt book. We take our commitment to
improving our content and products to meet your needs seriously—that's
why your feedback is so valuable. Whatever your feelings about your
purchase, please consider leaving a review on this book's Amazon page.
Not only will this help us, more importantly it will also help others in the
community to make an informed decision about the resources that they
invest in to learn. You can also review for us on a regular basis by
joining our reviewers' club. If you're interested in joining, or would
like to learn more about the benefits we offer, please contact us:
customerreviews@packtpub.com.
Preface
This book is about functional algorithms and data structures. Algorithms
and data structures are fundamentals of computer programming.
For example, reversing a singly linked list using three node pointers is a
well known algorithm. We scan the list once and reverse it by changing
the pointer fields of each node. The three pointer variables guide the
reversal process.
I have come across many such pointer tricks and have used them as
needed.
We slept easier, the code worked as expected, and all was well with the
world!
I could very well see why writing side-effect free code worked! I was
hooked and started playing with Scala, Clojure, and Erlang. Immutability
was the norm here.
All in good time though! Reading this book will help you see that we
need not sacrifice algorithmic performance while avoiding in-place
mutation!
You also need a text editor. Use whichever you are comfortable with.
Who this book is for
The book assumes some familiarity with basic data structures. You
should have played with fundamental data structures like linked lists,
heaps, and binary trees. It also assumes that you have written some code
in a functional language.
We try to site links that offer hands-on code snippets, so you can
practice them yourself.
A lot of thought has gone into making helpful diagrams. Quizzes and
exercises are included, so you can apply what you've learned.
All the code is available online. We strongly advocate keying in the code
snippets though, to internalize the principles and techniques.
Code words in text, database table names, folder names, filenames, file
extensions, pathnames, dummy URLs, user input, and Twitter handles
are shown as follows: "The following function f has a side effect,
though."
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: "Clicking the Next button moves you to the next screen."
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.
Once the file is downloaded, please make sure that you unzip or extract
the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
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.
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.
Questions
If you have a problem with any aspect of this book, you can contact us
at questions@packtpub.com, and we will do our best to address the
problem.
Exploring the Variety of Random
Documents with Different Content
a really first-class highly certificated magician from Cairo, or some
big town, and get him to come out and do the job. In the meantime,
as Qwaytin had told me that there were some mounds in the
Kairowin hattia, that we should go there through the eastern part of
the Farafra depression and see if they did not contain treasure.
Qwaytin had heard that they contained buildings, and so thought that
it would be a likely place for buried riches, though, as he said
lugubriously, he did not expect that we should find anything like what
we might have done if we had discovered the treasure of those three
Sultans. The following morning a rather crestfallen caravan set out
for the eastern side of Farafra.
CHAPTER XXIII
O N leaving the hill we took a road that led us towards the north.
We first rounded the western end of the scarp of the detached
plateau parallel to which we had marched on coming from Bu
Gerara, and, about two hours after our start, ascended a steepish
bank on to the top of the plateau, which here was only about fifty feet
high.
From the summit of a small hill close by, a huge cliff stretching to
the north and south, as far as it was possible to see, was visible, far
off in the east; this was evidently the eastern boundary of the Farafra
depression, and, as I afterwards discovered, the continuation of the
cliff to the north of Bu Gerara.
The scarp was too far for me to be able to see any details of its
surface, with the light behind it, and as the top of it showed as only a
straight line, there were no points on it to which I could take a
bearing.
In these circumstances it was impossible either to fix its position
or to estimate the direction in which it ran. I several times met with
this difficulty, but found that, when a cliff faced towards the south, it
was only necessary for me to wait till the sun came round far enough
to begin to light up its surface, and then a rough estimate of the
direction in which it ran could be obtained by taking a bearing on to
the sun itself. This dodge was especially useful when it was
necessary to map the continuation of a cliff, part of which had
already been surveyed and the remainder of it could only be seen
from one point, such as the top of a high hill.
The part of the Farafra depression in which we found ourselves
was an absolutely featureless plain, of hard level sand, that sloped
slightly towards the foot of the scarp on our east. Here and there we
came across patches of greenish clay, with white lines running
through it, showing above the surface of the sand.
The Persian King, Cambyses, during his occupation of Egypt,
sent a great army across the desert to destroy the oracle of Jupiter
Ammon in Siwa Oasis. The army never reached Siwa; but was lost
in the desert. Its last resting-place is unknown, but, according to
native reports, the whole host perished of thirst in this huge
depression in which the oasis of Farafra lies.
I happened to mention to Qwaytin the subject of singing sands,
and asked him if he had ever heard any. He told me that somewhere
in the north of the Farafra depression there was a rock that was
supposed to be the “church” of the spirits of the lost Persian army. It
was called the “infidel rock,” because it “sang on Sunday.” It
appeared to be some form of musical sands.
It was not until the third day after our start from the treasure hill
that we sighted in the west the field of dunes that occupies the
centre of the Farafra wady. They appeared to be almost white in
colour, and lay a long way off.
Qwaytin told me that we should reach the Kairowin hattia on our
third day after leaving his hill. It will give some idea of his utter
incompetence as a guide when I say that we did not actually get
there until two days later.
He came into my tent on the first evening and began yarning in an
aimless sort of way, as he generally did as a preliminary to serious
business, and I endeavoured to extract some information from him
as to the topography of the Bedayat country, with which he was well
acquainted.
But he at once got impatient and changed the subject to that of
his confounded hill. He ended by asking—almost demanding—that
we should go back there to have another look at it, and to make
certain that there was not another hill in the neighbourhood which
might be the one indicated in his book. On my refusing to do so, he
flounced out of the tent—he was certainly a queer customer to deal
with.
Whenever I spoke to him the next day he began gassing about his
wretched hill, and saying that he wanted to go back to it; but towards
evening he rather recovered himself, and when he came to my tent I
again threw out feelers about the country of the Bedayat, though he
declined to tell me anything about the district, he started giving me a
lot of information about the Bedayat themselves, which, as they are
an almost unknown race, proved extremely interesting.
They claim to be descended from an afrit, whom, for some crime,
either David or Solomon shut up in a box, till he grew to such an
enormous size that he burst it open. There still exists apparently a
mongrel Bedayat—Tibbu tribe, known as the M’Khiat er Rih, that
possess the miraculous power of being able to walk over sand
without leaving any tracks behind them—a most useful
accomplishment in the desert for a race of born freebooters. This
peculiarity they owe to the fact that wherever they go they are
followed by a wind that immediately obliterates their footprints!
On our fourth day after leaving the treasure hill, our road
converged towards the dunes lying on our west, and, as Qwaytin
seemed to be hopelessly lost, I climbed one of the biggest of them
with him to try and make out our position.
From the top, the east and west scarp, with a break in it leading
up to Baharia Oasis, that lies on the north of Farafra, could be seen
in the far distance, but no sign of the hattia Kairowin was visible. In
front of us, however, was a high three-headed sif, or longitudinal
sand dune, that Qwaytin declared to be the landmark for the hattia
from the south.
As we were getting very short of water, the news that the hattia
was not in sight caused something like consternation among my
men. They all started grumbling at Qwaytin’s ignorance of the road,
and Ibrahim went so far as to ask him point-blank why he called
himself a guide, if he knew so little about the desert.
This coming from a young Sudani, hardly out of his ’teens, to an
elderly Arab guide, who, moreover, was a sheykh of his tribe, was a
great ayb, and Qwaytin was intensely put out. Qway, under the
circumstances, would have retaliated with some stinging remarks on
the inferiority of “slaves” and the respect that was due from a boy to
his elders and superiors in rank; but Qwaytin lacked his ready
powers of vituperation. He was a slow-witted old curmudgeon, and
failed entirely to put Ibrahim in his place. His own men stood up for
him in a feeble sort of way. But they were no match for Ibrahim, and
eventually gave up any attempt to defend their sheykh, probably
feeling themselves that there was not much to be said in his
defence. As I rather wanted to encourage a certain amount of friction
between my men and Qwaytin’s, I left them to settle their differences
as best they could, with the result that Qwaytin and his men got
much the worst of the wrangle.
Kairowin hattia measures some eighteen miles from north to
south, by seven from east to west. It consists of a level scrub-
covered area, in which, here and there, are to be seen a few
neglected-looking palms. A number of wells have been sunk here at
various times; one on the extreme eastern edge of the hattia, where
the road coming from Assiut first enters the scrub, is known as Bir
Murr. This well, which I did not visit, is said to be sanded up. Another
well somewhere to the north, I believe, is known as Bir Abd el Qadr.
There are also several others, all of which seem to be impartially
named Bir Kairowin. Probably water can be found under all the lower
lying parts of the hattia by digging for a few feet into the ground,
which throughout this district consists of chalk.
The wells in every case apparently give water so thick with chalk
particles that when first drawn from them it is almost as milky as
whitewash. Attempts to clear the water by passing it through a
Berkefeld filter failed, as the chalk clogged the filter after a few
strokes. But when it had been allowed to stand for a few hours, most
of the chalk settled down to the bottom, and the water that was
poured off passed quite easily through the filter, after which it proved
to be of quite good quality.
I, unfortunately, forgot to wind my watches the first night in the
hattia, and so allowed the half chronometer I had been using in
taking my observations to run down. As I was depending on it for my
longitudes, this necessitated a stay of two or three days in the camp
in order to ascertain its new rate after it had been rewound.
These watches are for some reason only made so as to run for
one day. As oversights of this kind must be of common occurrence
with travellers, it would seem to be preferable that they should be
made so as to run for two days, and be furnished with an up and
down indicator to show how long an interval has elapsed since they
were last wound.
I spent a considerable part of the time while in the hattia in trying,
without success, to get a shot at gazelle. There appeared to be very
few in the district, though a considerable number of old tracks were
to be seen where they had been feeding on the scrub.
This scarcity of game may perhaps have been due to the fact that
a few bedawin were at that time living there in charge of some
camels belonging to the Senussi zawia at Qasr Farafra. These men
kept away from the camp, but I saw them and their camels several
times wandering about in the scrub, and twice found small hovels
constructed of brushwood, in which they had been living—they had,
so far as I could see, no tents.
My men spent most of their time in grubbing about in some large
mounds. On the top of one of these, about thirty feet high, Ibrahim
found some burnt bricks. The whole mound was covered by a thick
growth of terfa bushes, among which the sand had collected,
completely hiding any building there might have been beneath it.
It must have been originally a building of some size and of
considerable height, and was perhaps a tower. The men unearthed
part of a small room at the base of the mound. It had been well built,
of the same burnt bricks, and the interior was covered with plaster. A
few pieces of broken pottery were found, one of them covered with a
green glaze. There were four or five other mounds of a similar nature
in the neighbourhood; but we had neither time nor implements
thoroughly to examine them.
As the total result of their treasure hunt in Kairowin the men only
unearthed one corpse and a few bits of broken pottery, without
finding even a single copper coin to gratify their cupidity. They were
consequently considerably disillusioned with their occupation, and I
experienced no difficulty in getting them to start for Qasr Farafra.
I made first for the main well, that is known as the Bir Kairowin, in
order to close my traverse. The water lay about eight feet below the
surface; access being gained to it by the usual sloping path, cut out
of one of its sides. By the top of the well was a mud-built trough for
watering camels, with an empty paraffin tin lying beside it for use as
a bucket.
Immediately on leaving the hattia we got into the dunes, which
cover a large area in the centre of the Farafra depression. The first
two or three dunes gave a little difficulty, but we found the rest of
them quite easy to cross. They were all, so far as I could see, of a
very elongated whalebacked type, which ran roughly from north to
south, in the direction of the prevailing wind.
Qasr Farafra lay almost due west from our camp. Soon after we
got into the sand it became clear that Qwaytin was again hopelessly
lost, as I found we were marching almost due south. I was obliged to
put it to my guide, as inoffensively as I could, that if he would change
the direction in which he was leading us by a mere right angle, we
might perhaps reach our destination, instead of going on to Dakhla
Oasis as we seemed to be doing. Qwaytin was so hopelessly lost
that he accepted my suggestion without the slightest argument.
Soon after this we got out of the sand on to level desert, where a
large number of black nodules of iron pyrites were to be seen lying
on the surface. Further on some fine specimens of sand erosion
were met with in the shape of chalk “mushrooms” and table rocks.
Otherwise this part of the desert was quite featureless. The road lay
entirely over white chalk, which caused a rather trying glare in the
blazing sunlight.
We sighted Qasr Farafra on the evening of the second day after
leaving Kairowin hattia; but as night fell before we could reach it, we
camped a few miles away from the village. Two hours’ march on the
following morning brought us into the oasis. On the outskirts we
passed a patch of ground on which the sand was encroaching, some
palms lying on the north of it being almost entirely submerged.
We camped on the northern side of the village. A large crowd of
natives came out and stood watching us while the tent was being
pitched. Among them was a sulky-looking fellow whom I was told
was the ’omda; so, as soon as the tent was pitched, I invited him and
some of the other men standing by to come in.
We had foolishly camped too close to the village, with the result
that throughout the greater part of the day the camp was surrounded
by a crowd of men and children watching all our actions, peering into
the tent, thronging round the theodolite, when I began to take
observations, and generally showing an ill-mannerly curiosity that
was in great contrast to the conduct of the natives of the other oases
in which we stayed. Farafra being the least known of the Egyptian
oases, the advent of a European was an event of such rare
occurrence that the natives had evidently decided to make the most
of it.
The natives of Farafra Oasis, who are known as the Farfaroni, or
sometimes as the Farafaroni, are a far more vigorous lot than those
of Kharga and Dakhla. They were a surly unpleasant-looking crowd.
The day after our arrival, I went out with the ’omda and Qwaytin to
see the village and plantations. With the exception of an ezba at ’Ain
Sheykh Murzuk, where there are a few houses, a Senussi zawia and
a family or two continuously resident to tend the cultivation near the
well, Qasr Farafra is the only permanently inhabited spot in the
whole Farafra depression. It is a poor little place with a total
population of about five hundred and fifty inhabitants. The houses
are of the usual mud-built type, and in most cases little better than
huts; almost the only exception being that of a square tower,
showing in places the remains of battlements, attributed, perhaps
rightly, by the natives to the Romans, who are said to have erected it
as a keep to protect the village.
This proved to be rather an interesting place. It is not inhabited,
but the door is kept locked with a watchman perpetually on guard
over it. The building is used solely as a storehouse, each family in
the village having the right to the use of one of the rooms that it
contains—there were said to be no less than one hundred and
twenty-five chambers in the building.
The ’omda showed us over the tower. The entrance lay through a
strong wooden door, at the top of a flight of steps, in a passage
entered in the middle of one of the outer walls, the walls on either
side of which were pierced with apertures, apparently intended for
use as loop-holes. The passage extended the whole height of the
building and was unroofed, in order that stones might be dropped
from above on to any assailant attempting to attack the door.
BOY WITH CROSS-BOW, FARAFRA.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebooknice.com