100% found this document useful (1 vote)
11 views61 pages

Learning Functional Data Structures and Algorithms Learn functional data structures and algorithms for your applications and bring their benefits to your work now 1st Edition Atul S. Khot instant download

The document presents an overview of the book 'Learning Functional Data Structures and Algorithms' by Atul S. Khot and Raju Kumar Mishra, which aims to teach functional data structures and algorithms for practical applications. It includes links to various related resources and books on data structures and algorithms across different programming languages. The book emphasizes the benefits of functional programming and provides a comprehensive guide to implementing these concepts effectively.

Uploaded by

lnyogjht478
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 (1 vote)
11 views61 pages

Learning Functional Data Structures and Algorithms Learn functional data structures and algorithms for your applications and bring their benefits to your work now 1st Edition Atul S. Khot instant download

The document presents an overview of the book 'Learning Functional Data Structures and Algorithms' by Atul S. Khot and Raju Kumar Mishra, which aims to teach functional data structures and algorithms for practical applications. It includes links to various related resources and books on data structures and algorithms across different programming languages. The book emphasizes the benefits of functional programming and provides a comprehensive guide to implementing these concepts effectively.

Uploaded by

lnyogjht478
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/ 61

Learning Functional Data Structures and

Algorithms Learn functional data structures and


algorithms for your applications and bring their
benefits to your work now 1st Edition Atul S.
Khot download
https://textbookfull.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-1st-edition-atul-s-khot/

Download full version ebook from https://textbookfull.com


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

Learning functional data structures and algorithms


learn functional data structures and algorithms for
your applications and bring their benefits to your work
now Khot
https://textbookfull.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-khot/

Probabilistic data structures and algorithms for big


data applications Gakhov

https://textbookfull.com/product/probabilistic-data-structures-
and-algorithms-for-big-data-applications-gakhov/

Data Structures and Algorithms in Swift Kevin Lau

https://textbookfull.com/product/data-structures-and-algorithms-
in-swift-kevin-lau/

Data Structures & Algorithms in Python John Canning

https://textbookfull.com/product/data-structures-algorithms-in-
python-john-canning/
A Common Sense Guide to Data Structures and Algorithms
1st Edition Jay Wengrow

https://textbookfull.com/product/a-common-sense-guide-to-data-
structures-and-algorithms-1st-edition-jay-wengrow/

Data Structures Algorithms in Kotlin Implementing


Practical Data Structures in Kotlin 1st Edition
Raywenderlich Tutorial Team

https://textbookfull.com/product/data-structures-algorithms-in-
kotlin-implementing-practical-data-structures-in-kotlin-1st-
edition-raywenderlich-tutorial-team/

Data Structures Algorithms in Go 1st Edition Hemant


Jain

https://textbookfull.com/product/data-structures-algorithms-in-
go-1st-edition-hemant-jain/

Codeless Data Structures and Algorithms: Learn DSA


Without Writing a Single Line of Code Armstrong Subero

https://textbookfull.com/product/codeless-data-structures-and-
algorithms-learn-dsa-without-writing-a-single-line-of-code-
armstrong-subero/

Algorithms and Data Structures in Action MEAP V12


Marcello La Rocca

https://textbookfull.com/product/algorithms-and-data-structures-
in-action-meap-v12-marcello-la-rocca/
Learning Functional Data
Structures and Algorithms

Learn functional data structures and algorithms for


your applications and bring their benefits to your work
now

Atul S. Khot
Raju Kumar Mishra

BIRMINGHAM - MUMBAI
Learning Functional Data Structures and
Algorithms
Copyright © 2017 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 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.

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: February 2017

Production reference: 1170217

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-873-1
www.packtpub.com
Credits

Authors Copy Editor


Atul S. Khot Gladson Monteiro
Raju Kumar Mishra

Reviewer Project Coordinator


Muhammad Ali Ejaz Sheejal Shah

Commissioning Editor Proofreader


Kunal Parikh Safis Editing

Acquisition Editor Indexer


Denim Pinto Mariammal Chettiyar

Content Development Editor Graphics


Nikhil Borkar Abhinash Sahu

Technical Editor Production Coordinator


Hussain Kanchwala Shantanu Zagade
About the Authors
Atul S. Khot grew up in Marathwada, a region of the state of Maharashtra, India. A self-
taught programmer, he started writing software in C and C++. A Linux aficionado and a
command-line guy at heart, Atul has always been a polyglot programmer. Having
extensively programmed in Java and dabbled in multiple languages, these days, he is
increasingly getting hooked on Scala, Clojure, and Erlang. Atul is a frequent speaker at
software conferences, and a past Dr. Dobb's product award judge. In his spare time, he
loves to read classic British detective fiction. He is a foodie at heart and a pretty good cook.
Atul someday dreams of working as a master chef, serving people with lip-smacking
dishes.

He was the author of Scala Functional Programming Patterns published by Packt Publishing
in December 2015. The book looks at traditional object-oriented design patterns and shows
how we could use Scala's functional features instead.

I would like to thank my mother, late Sushila S. Khot, for teaching me the value of sharing.
Aai, I remember all you did for the needy girl students! Your support for the blind school -
you brought hope to so many lives! You are no more, however your kindness and selfless
spirit lives on! I know you are watching dear mother, and I will carry on the flame till I
live! I also would like to thank my father, late Shriniwas V. Khot. Anna, I have a photo of
the 'Tamra pat'--an engraved copper plaque--commemorating your great contribution to
the country's freedom struggle. You never compromised on core values --always stood for
the needy and poor. You live on in my memories--a hero forever! I would also want to
thank Martin Odersky for giving us the Scala programming language. I am deeply
thankful to Rich Hickey and the Clojure community for their work on persistent data
structures. Chris Okasaki’s "Purely Functional Data Structures" is a perennial source of
inspiration and insight. I wish to thank Chris for writing the book. This book is influenced
by many ideas Chris presented in his book. I also wish to thank the functional
programming community for all the technical writings which is a source of continual
learning and inspiration. I would love to express my heartfelt thanks to Nikhil Borkar for
all the support through out the book writing. I also would take this opportunity to thank
Hussain Kanchwala for the detailed editing efforts to make the book perfect. You guys are
awesome! Thanks to y’all!
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.

My heartiest thanks to the Almighty. I would like to thank my mom, Smt. Savitri Mishra,
my sisters, Mitan and Priya, and my maternal uncle, Shyam Bihari Pandey, for their
support and encouragement. I am grateful to Anurag Pal Sehgal, Saurabh Gupta, and all
my friends. Last but not least, thanks to Nikhil Borkar, Content Development Editor at
Packt Publishing for his support in writing this book.
About the Reviewer
Muhammad Ali Ejaz is currently pursuing his graduate degree at Stony Brook University.
His experience, leading up to this academic achievement, ranges from working as a
developer to cofounding a start-up, from serving in outreach organizations to giving talks
at various prestigious conferences. While working as a developer at ThoughtWorks, Ali
cofounded a career empowerment based start-up by providing photographers a platform to
showcase their art and be discovered by potential employers. His passion for computer
science is reflected in his contributions to open source projects, such as GoCD, and his role
in serving as the cofounder and Community Outreach Director of a non-profit organization,
"Women Who Code - Bangalore Chapter". Along with this, he has also been given the
opportunity to speak at different conferences on Continuous Integration and Delivery
practices.

When he is not coding, he enjoys traveling, reading, and tasting new cuisine. You can
follow him on Twitter at @mdaliejaz.

I want to thank my Mom and Dad, who have always been my inspiration. I’d also like to
thank Ahmad and Sana, my siblings, who have been a constant source of cheerful support.
A lot of what I am today is because of them.
www.PacktPub.com
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://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: [email protected].
Table of Contents
Preface 1
Chapter 1: Why Functional Programming? 8
The imperative way 9
Higher level of abstraction 10
Functional programming is declarative 13
No boilerplate 14
Higher order functions 16
Eschewing null checks 17
Controlling state changes 19
Recursion aids immutability 21
Copy-on-write 23
Laziness and deferred execution 24
Composing functions 26
Summary 29
Chapter 2: Building Blocks 30
The Big O notation 30
Space/time trade-off 33
A word frequency counter 34
Matching string subsets 36
Referential transparency 40
Vectors versus lists 42
Updating an element 46
Not enough nodes 47
Complexities and collections 48
The sliding window 48
Maps 49
Persistent stacks 51
Persistent FIFO queues 52
Sets 53
Sorted set 54
Summary 55
Chapter 3: Lists 56
First steps 57
List head and tail 61
Drop elements 64
Concatenating lists 66
Persistent data structures 69
Tail call optimization 70
List append 72
List prepend 74
Getting value at index 76
Modifying a list value 78
Summary 80
Chapter 4: Binary Trees 81
Node definitions 82
Building the tree 84
Size and depth 86
Complete binary trees 88
Comparing trees 89
Flipping a binary tree 91
Binary tree traversal 93
The accumulator idiom 95
Binary Search Trees 98
Node insertion 99
Searching a key 101
Updating a value 101
Exercising it 102
Summary 103
Chapter 5: More List Algorithms 104
Binary numbers 104
Addition 107
Multiplication 110
Greedy algorithms and backtracking 113
An example of a greedy algorithm 115
The backtracking jig 116
Summary 119
Chapter 6: Graph Algorithms 120
Reversing a list 121
Graph algorithms 123
Graph traversal 124
Avoiding list appending 128

[ ii ]
Topological sorting 129
Cycle detection 132
Printing the cycle 133
Summary 134
Chapter 7: Random Access Lists 136
Incrementing a binary number 137
Adding two binary numbers 139
List of tree roots 140
Insertion 142
Lookup 145
Removal, head, and tail 148
Update 151
Summary 152
Chapter 8: Queues 154
Understanding FIFO queues 155
Functional FIFO queues 156
Invariants 158
Implementing a priority queue 159
Understanding priority queues/heaps 161
Leftist trees 164
Functional heaps 166
Summary 173
Chapter 9: Streams, Laziness, and Algorithms 175
Program evaluation 176
Eager evaluation 176
Argument evaluation 178
Lazy evaluation 179
Lazy evaluation in Scala 180
Lazy evaluation in Clojure 182
Memoization – remembering past results 186
Memoization in Scala 188
Memoization in Clojure 190
Memoizing simpleFactFun 191
Streams 192
Stream in Scala 192
Indexing the elements of a stream 193
Creation of an infinite length stream 193
Stream is immutable 195
Creating a stream from another 196

[ iii ]
Stream to list 197
Appending one stream to another 198
Length of a stream 198
Some mathematical functions of the stream class 198
Some more methods of the stream class 199
Streams (lazy sequence) in Clojure 199
Creating a memoized function of lazy sequences in Clojure 200
Some algorithms on stream 200
Arithmetic progression 201
Arithmetic progression in Scala 202
Arithmetic progression in Clojure 202
Standard Brownian motion 203
Standard Brownian motion in Scala 203
Standard Brownian motion in Clojure 204
Fibonacci series 205
First form of Fibonacci series 205
Second form of Fibonacci series 205
Fibonacci series in Scala 206
Fibonacci series in Clojure 207
Summary 208
Chapter 10: Being Lazy - Queues and Deques 209
Imperative implementations 211
Amortization 212
Problem with queues 213
Strict versus lazy 214
Streams 215
Streams meet queues 217
A sense of balance 220
Amortized deques 221
Summary 225
Chapter 11: Red-Black Trees 227
Terminology 228
Almost balanced trees 229
The concept of rotation 229
Red-Black trees 231
Inserting a node 234
The Black-Red-Red path 237
Left, left – red child and grand child 238
Left child, right grand child 240
Right child, right grand child 241

[ iv ]
Right, left 242
Verifying the transformation 244
Complexity 245
Summary 246
Chapter 12: Binomial Heaps 247
Binomial trees 249
Left child, right sibling 252
A binomial heap 253
Linking up 254
Inserting a value 256
Binary number equivalence 259
Merging 260
Find the minimum 261
Deleting the minimum 262
Exercising the code 263
Complexity 264
Summary 265
Chapter 13: Sorting 266
Stable and unstable sorting 267
Stable sorting 268
Unstable sorting 268
Bubble sort 269
Scala implementation of bubble sort 272
Complexity of bubble sort 274
Selection sort 274
Complexity of selection sort 278
Insertion sort 278
Complexity of insertion sort 282
Merge sort 282
Splitting the sequence 283
Merging two sorted subsequences 285
Complexity of merge sort 289
Quick sort 289
Partition 290
Complexity of quick sort 293
Summary 293
Index 294

[v]
Preface
This book is about functional algorithms and data structures. Algorithms and data
structures are fundamentals of computer programming.

I started my career writing C and C++ code. I always enjoyed designing efficient algorithms.
I have experienced many an Aha! moments, when I saw how powerful and creative pointer
twiddling could be!

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.

I was next initiated into the world of multi-threading! Variables became shared states
between threads! My bagful of tricks was still valid; however, changing state needed a lot of
care, to stay away from insidious threading bugs.

The real world is never picture perfect and someone forgot to synchronize a data structure.

Thankfully we started using C++, which had another bagful of tricks, to control the state
sharing. You could now make objects immutable!

For example, we were able to implement the readers/writer locking pattern effectively.
Immutable objects could be shared without worry among thousands of readers!

We slept easier, the code worked as expected, and all was well with the world!

I soon realized the reason it worked well! Immutability was finally helping us better
understand the state changes!
Preface

The sands of time kept moving and I discovered functional programming.

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.

However, I wondered how the traditional algorithms would look like in a functional
setting--and started learning about it.

A data structure is never mutated in place. Instead, a new version of the data structure is
created. The strategy of copy on write with maximized sharing was an intriguing one! All
that careful synchronization is simply not needed!

The languages come equipped with garbage collection. So, if a version is not needed
anymore, the runtime would take care of reclaiming the memory.

All in good time though! Reading this book will help you see that we need not sacrifice
algorithmic performance while avoiding in-place mutation!

What this book covers


Chapter 1, Why Functional Programming?, takes you on a whirlwind tour of the functional
programming (FP) paradigm. We try to highlight the many advantages FP brings to the
table when compared with the imperative programming paradigm. We discuss FP’s higher
level of abstraction, being declarative, and reduced boilerplate. We talk about the problem
of reasoning about the state change. We see how being immutable helps realize "an easier to
reason about system".

Chapter 2, Building Blocks, provides a whirlwind tour of basic concepts in algorithms. We


talk about the Big O notation for measuring algorithm efficiency. We discuss the space time
trade-off apparent in many algorithms. We next look at referential transparency, a
functional programming concept. We will also introduce you to the notion of persistent
data structures.

Chapter 3, Lists, looks at how lists are implemented in a functional setting. We discuss the
concept of persistent data structures in depth here, showing how efficient functional
algorithms try to minimize copying and maximize structural sharing.

Chapter 4, Binary Trees, discusses binary trees. We look at the traditional binary tree
algorithms, and then look at Binary Search Trees.

[2]
Preface

Chapter 5, More List Algorithms, shows how the prepend operation of lists is at the heart of
many algorithms. Using lists to represent binary numbers helps us see what lists are good
at. We also look at greedy and backtracking algorithms, with lists at the heart.

Chapter 6, Graph Algorithms, looks at some common graph algorithms. We look at graph
traversal and topological sorting, an important algorithm for ordering dependencies.

Chapter 7, Random Access Lists, looks at how we could exploit Binary Search Trees to access
a random list element faster.

Chapter 8, Queues, looks at First In First Out (FIFO) queues. This is another fundamental
data structure. We look at some innovative uses of lists to implement queues.

Chapter 9, Streams, Laziness, and Algorithms, looks at lazy evaluation, another FP feature.
This is an important building block for upcoming algorithms, so we refresh ourselves with
some deferred evaluation concepts.

Chapter 10, Being Lazy – Queues and Deques, looks at double-ended queues, which allow
insertion and deletion at both ends. We first look at the concept of amortization. We use
lazy lists to improve the queue implementation presented earlier, in amortized constant
time. We implement deques also using similar techniques.

Chapter 11, Red-Black Trees, shows how balancing helps avoid degenerate Binary Search
Trees. This is a comparatively complex data structure, so we discuss each algorithm in
detail.

Chapter 12, Binomial Heaps, covers heap implementation offering very efficient merge
operation. We implement this data structure in a functional setting.

Chapter 13, Sorting, talks about typical functional sorting algorithms.

What you need for this book


You need to install Scala and Clojure. All the examples were tested with Scala version
2.11.7. The Clojure examples were tested with Clojure version 1.6.0. You don’t need any
IDE as most of the examples are small enough, so you can key them in the REPL
(Read/Eval/Print Loop).

You also need a text editor. Use whichever you are comfortable with.

[3]
Preface

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.

Scala is used as an implementation language. We do highlight related Clojure features too.


The idea is to illustrate the basic design principles.

We explain the language concepts as needed. However, we just explain the basics and give
helpful pointers, so you can learn more by reading the reference links.

We try to site links that offer hands-on code snippets, so you can practice them yourself.

Walking through an algorithm and discussing the implementation line by line is an


effective aid to understanding.

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.

Welcome to the wonderland of functional data structures and algorithms!

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: "The
following function f has a side effect, though."

A block of code is set as follows:


user=> (def v [7 11 19 52 42 72])
#'user/v
user=> (def v1 (conj v 52))
#'user/v1

[4]
Preface

If there is a line (or lines) of code that needs to be highlighted, it is set as follows:
scala> def pop(queue: Fifo): (Int, Fifo) = {
| queue.out match {
| case Nil => throw new IllegalArgumentException("Empty queue");
| case x :: Nil => (x, queue.copy(out = queue.in.reverse, Nil))
| case y :: ys => (y, queue.copy(out = ys))
| }
| }
pop: (queue: Fifo)(Int, Fifo)

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

Warnings or important notes appear in a box like this.

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.

[5]
Preface

Downloading the example code


You can download the example code files for this book from your account at http://www.p
acktpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.c
om/supportand register to have the files e-mailed directly to you.

You can download the code files by following these steps:

1. Log in or register to our website using your e-mail address and password.
2. Hover the mouse pointer on the SUPPORT tab at the top.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box.
5. Select the book for which you're looking to download the code files.
6. Choose from the drop-down menu where you purchased this book from.
7. Click on Code Download.

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

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPubl
ishing/Learning-Functional-Data-Structures-and-Algorithms. We also have other
code bundles from our rich catalog of books and videos available at https://github.com/P
acktPublishing/. Check them out!

Downloading the color images of this book


We also provide you with a PDF file that has color images of the screenshots/diagrams used
in this book. The color images will help you better understand the changes in the output.
You can download this file from https://www.packtpub.com/sites/default/files/down
loads/LearningFunctionDataStructuresandAlgorithms_ColorImages.pdf.

[6]
Preface

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/conten


t/supportand 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.

[7]
Why Functional Programming?
1
What is functional programming (FP)? Why is it talked about so much?

A programming paradigm is a style of programming. FP is a programming paradigm


characterized by the absence of side effects.

In FP, functions are the primary means of structuring code. The FP paradigm advocates
using pure functions and stresses on immutable data structures. So we don't mutate variables,
but pass a state to function parameters. Functional languages give us lazy evaluation and
use recursion instead of explicit loops. Functions are first-class citizens like numbers or
strings. We pass functions as argument values, just like a numeric or string argument. This
ability to pass functions as arguments allows us to compose behavior, that is, cobble
together something entirely new from existing functions.

In this chapter, we will take a whirlwind tour of functional programming. We will look at
bits of code and images to understand the concepts. This will also lay a nice foundation for
the rest of the book. We will use the functional paradigm and see how it changes the way
we think about data structures and algorithms.

This chapter starts with a look at the concept of abstraction. We will see why abstractions
are important in programming. FP is a declarative style of programming, similar to
Structured Query Language (SQL). Because it is declarative, we use it to tell what we want
the computer to do, rather how it should do it. We will also see how this style helps us stay
away from writing common, repetitive boilerplate code.
Why Functional Programming?

Passing functions as arguments to other, higher order functions is the central idea in FP; we
look at this next. We will also see how to stay away from null checks. Controlled state
change allows us to better reason our code. Being immutable is the key for creating code
that would be easier to reason about.

Next, we will see how recursion helps us realize looping without mutating any variables.
We will wrap up the chapter with a look at lazy evaluation, copy-on-write, and functional
composition.

The imperative way


We keep contrasting FP with the imperative style of programming. What do we mean by
imperative style, though?

The imperative programming style is embodied by a sequence of commands modifying a


program's state. A simple example of this is a for loop. Consider the following pseudo code
snippet to print all the elements of an array:
x = [1,2,3,4...] // an array, x.size tells the number of array elements
for( int i = 0; i < x.size; ++i ) {
println(x[i])
}

Here is a pictorial rendering of the concepts:

[9]
Why Functional Programming?

As the figure shows, the for loop establishes an initial state by setting the variable i to 0.
The variable is incremented every time the loop is repeated; this is what we mean by the
state being modified. We keep reading and modifying the state, that is, the loop variable,
until there are no elements left in the array.

FP advocates staying away from any state modification. It gives us tools so we don't worry
about how to loop over a collection; instead, we focus on what we need to do with each
element of the collection.

Higher level of abstraction


FP allows us to work at a higher level of abstraction. Abstraction is selective ignorance. The
world we know of runs on abstractions. If we say, “Give me sweet condensed milk frozen
with embedded dry fruits' someone might really have a hard time understanding it.
Instead, just say “ice-cream”! Aha! It just falls into place and everyone is happy.

Abstractions are everywhere. An airplane is an abstraction, so is a sewing machine or a


train. When we wish to travel by train, we buy a ticket, board the train, and get off at the
destination. We really don't worry about how the train functions. We simply can't be
expected to deal with all the intricacies of a train engine. As long as it serves our purpose,
we ignore details related to how an engine really works.

What are the benefits of an abstraction? We don't get bogged down into unnecessary
details. Instead, we focus on the task at hand by applying higher level programming
abstractions.

Compare the preceding for loop with the functional code snippet:
scala> val x = Array(1,2,3,4,5,6)
x: Array[Int] = Array(1, 2, 3, 4, 5, 6)
scala> x.foreach(println _)
1
2
...

We simply focus on the task at hand (print each element of an array) and don't care about
the mechanics of a for loop. The functional version is more abstract.

[ 10 ]
Why Functional Programming?

As software engineers, when we implement an algorithm and run it, we are intentionally
ignoring many details.

We know that the preceding sandwich stack somehow works and faithfully translates the
algorithm into runnable code.

Applying higher level abstractions is commonly done in functional languages. For example,
consider the following Clojure REPL snippet:
user=> ((juxt (comp str *) (comp str +)) 1 2 3 4 5)
["120" "15"]

[ 11 ]
Why Functional Programming?

We are juxtaposing two functions; each of these are in turn composed of the str function
and an arithmetic function:

We just don't worry about how it works internally. We just use high-level abstractions
cobbled together with existing pieces of abstract functionality.

We will be looking at abstract data types (ADT) closely in this book. For example, when we
talk about a stack, we think of the Last In First Out (LIFO) order of access. However, this
ADT is realized by implementing the stack via a data structure, such as a linked list or an
array.

[ 12 ]
Why Functional Programming?

Here is a figure showing the First In First Out (FIFO) ADT in action. The FIFO queue is the
normal queue we encounter in life, for example, queuing up at a booking counter. The
earlier you get into a queue, the sooner you get serviced.

The FIFO queue is an ADT. True that we think of it as an ADT; however, as shown in the
preceding diagram, we can also implement the queue backed by either an array or a linked
list.

Functional programming is declarative


When we use SQL, we just express our intent. For example, consider this:
mysql> select count(*) from book where author like '%wodehouse%';

We just say what we are looking for. The actual mechanism that gets the answer is hidden
from us. The following is a little too simplistic but suitable example to prove the point.

[ 13 ]
Why Functional Programming?

The SQL engine will have to loop over the table and check whether the author column
contains the wodehouse string. We really don't need to worry about the search algorithm.
The author table resides on a disk somewhere. The number of table rows that need to be
filtered could easily exceed the available memory. The engine handles all such complexities
for us though.

We just declare our intent. The following Scala snippet is declarative. It counts the number of
even elements in the input list:
scala> val list = List(1, 2, 3, 4, 5, 6)
list: List[Int] = List(1, 2, 3, 4, 5, 6)

scala> list.count( _ % 2 == 0 )
res0: Int = 3

The code uses a higher order function, namely count. This takes another function, a
predicate, as an argument. The line loops over each list element, invokes the argument
predicate function, and returns the count.

Here is another example of Clojure code that shows how to generate a combination of
values from two lists:
user=> (defn fun1 [list1 list2]
#_=> (for [x list1 y list2]
#_=> (list x y)))
#'user/fun1
user=> (fun1 '(1 2 3) '(4 5 6))
((1 4) (1 5) (1 6) (2 4) (2 5) (2 6) (3 4) (3 5) (3 6))

Note the code used to generate the combination. We use for comprehension to just state what
we need done and it would be done for us.

No boilerplate
Boilerplate code consists sections of the same code written again and again. For example,
writing loops is boilerplate, as is writing getters and setters for private class members.

[ 14 ]
Why Functional Programming?

As the preceding code shows, the loop is implicit:


scala> List(1, 2, 3, 4, 5) partition(_ % 2 == 0)
res3: (List[Int], List[Int]) = (List(2, 4),List(1, 3, 5))

We just wish to separate the odd and even numbers. So we just specify the criteria via a
function, an anonymous function in this case. This is shown in the following image:

What is boilerplate? It is a for loop, for example. In the imperative world, we code the loop
ourselves. We need to tell the system how to iterate over a data structure.

Isn't Scala code just to the point? We tell what we need and the loop is implied for us. No
need to write a for loop, no need to invent a name for the loop variable, and so on. We just
got rid of the boilerplate.

Here is a Clojure snippet that shows how to multiply each element of a vector by 2:
user=> (map * (repeat 2) [1 2 3 4 5])
(2 4 6 8 10)

The map function hides the loop from us. Then (repeat 2) function call generates an
infinite sequence.

[ 15 ]
Discovering Diverse Content Through
Random Scribd Documents
I.
THE LITTLE MASTER.

If you imagine that the book called "The Story of Aaron (so-named),
the Son of Ben Ali" tells all the adventures of the Arab while he was
a fugitive in the wildwoods, you are very much mistaken. If you will
go back to that book you will see that Timoleon the black stallion,
Grunter the white pig, Gristle the gray pony, and Rambler the track
dog, told only what they were asked to tell. And they were not
anxious to tell even that. They would much rather have been left
alone. What they did tell they told without any flourishes whatever,
for they wanted to get through and be done with it. Story-telling was
not in their line, and they knew it very well; so they said what they
had to say and that was the end of it so far as they were concerned:
setting a worthy example to men and women, and to children, too.
It is natural, therefore, that a man such as Aaron was, full of
courage and valuable to the man who had bought him from the
speculator, should have many adventures that the animals knew
nothing of, or, if they knew, had no occasion to relate. In the book
you will find that Buster John and Sweetest Susan asked only about
such things as they heard of incidentally. But some of the most
interesting things were never mentioned by Aaron at all;
consequently the children never asked about them.
Little Crotchet, it will be remembered, who knew more about the
matter than anybody except Aaron, was dead, and so there was
nobody to give the children any hint or cue as to the questions they
were to ask. You will say they had Aaron close at hand. That is true,
but Aaron was busy, and besides that he was not fond of talking,
especially about himself.
And yet, the most of the adventures Aaron had in the wildwoods
were no secret. They were well known to the people in the
neighborhood, and for miles around. In fact, they were made the
subject of a great deal of talk in Little Crotchet's day, and many men
(and women too) who were old enough to be wise shook their heads
over some of the events and declared that they had never heard of
anything more mysterious. And it so happened that this idea of
mystery deepened and grew until it made a very romantic figure of
Aaron, and was a great help to him, not only when he was a fugitive
in the wildwoods, but afterwards when he "settled down," as the
saying is, and turned his attention to looking after affairs on the
Abercrombie plantation.
All this happened before Buster John and Sweetest Susan were
born, while their mother was a girl in her teens. When Little Crotchet
was alive things on the Abercrombie plantation were very different
from what they were before or afterward. It is true the lad was a
cripple and had to go on crutches, except when he was riding
Gristle, the Gray Pony. But he was very active and nimble, and very
restless, too, for he was here, there, and everywhere. More than
that, he was always in a good humor, always cheerful, and most of
the time laughing at his own thoughts or at something he had
heard. For it was well understood on that plantation, and, indeed,
wherever little Crotchet was familiarly known, that, as he was
something of an invalid, and such a little bit of a fellow to boot,
nothing unpleasant was to come to his ears. If he found out about
trouble anywhere he was to find it out for himself, and without help
from anybody else.
But although little Crotchet was small and crippled, he had a very
wise head on his shoulders. One of the first things he found out was
that everybody was in a conspiracy to prevent unpleasant things
from coming to his ears, and the idea that he was to be humbugged
in this way made him laugh, it was so funny. He said to himself that
if he could have troubles while everybody was trying to help him
along and make life pleasant for him, surely other people who had
nobody to look out for them must have much larger troubles. And he
found it to be true, although he never said much about it.
The truth is that while people thought they were humbugging little
Crotchet, he was humbugging everybody except a few who knew
what a shrewd little chap he was. These few had found out that little
Crotchet knew a great deal more about the troubles that visit the
unfortunate in this world than anybody knew about his troubles—
and he had many.
It was very peculiar. He would go galloping about the plantation on
the Gray Pony, and no matter where he stopped there was always a
negro ready to let down the bars or the fence. How could this be?
Why, it was the simplest matter in the world. It made no difference
where the field hands were working, nor what they were doing, they
were always watching for their Little Master, as they called him. They
were sure to know when he was coming—sure to see him; and no
matter how high the fence was, down it would come whenever the
Gray Pony was brought to a standstill.
It was a sight to see the hoe hands or the plow hands when their
Little Master went riding among them. It was hats off and "howdy,
honey," with all, and that was something the White-Haired Master
never saw unless he was riding with Little Crotchet, which
sometimes happened. Once the White-Haired Master said to Little
Crotchet, "They all love you because you are good, my son." But
Little Crotchet was quick to reply:—
"Oh, no, father; it isn't that. It's because I am fond of them!"
Now, wasn't he wise for his age? He had stumbled upon the great
secret that makes all the happiness there is in this world. The
negroes loved him because he was fond of them. He used to sit on
the Gray Pony and watch the hands hoeing and plowing; and
although they did their best when he was around, he never failed to
find out the tired ones and send them on little errands that would
rest them. To one it was "Get me a keen switch." To another, "See if
you can find me any flowers."
One of the worst negroes on the plantation was Big Sal, a mulatto
woman. She had a tongue and a temper that nothing could conquer.
Once Little Crotchet, sitting on the Gray Pony, saw her hoeing away
with a rag tied around her forehead under her head handkerchief. So
he called her out of the gang, and she came with no very good
grace, and only then because some of the other negroes shamed
her into it. No doubt Little Crotchet heard her disputing with them,
but he paid no attention to it. When Big Sal came up, he simply said:

"Help me off the horse. I have a headache sometimes, and I feel it
coming on now. I want you to sit here and rub my head for me if
you are not too tired."
"What wid?" cried big Sal. "My han's too dirty."
"You get the headache out, and I'll get the dirt off," said Little
Crotchet, laughing.
Big Sal laughed too, cleaned her hands the best she could, and
rubbed the youngster's head for him, while the Gray Pony nibbled
the crabgrass growing near. But presently, when Little Crotchet
opened his eyes, he found that Big Sal was crying. She was making
no fuss about it, but as she sat with the child's head in her lap the
tears were streaming down her face like water.
"What are you crying about?" Little Crotchet asked.
"God A'mighty knows, honey. I'm des a-cryin', an' ef de angels fum
heav'm wuz ter come down an' ax me, I couldn't tell um no mo' dan
dat."
This was true enough. The lonely heart had been touched without
knowing why. But Little Crotchet knew.
"I reckon it's because you had the headache," he said.
"I speck so," answered Big Sal. "It looked like my head'd bust when
you hollered at me, but de pain all done gone now."
"I'm glad," replied Little Crotchet. "I hope my head will quit aching
presently. Sometimes it aches all night long."
"Well, suh!" exclaimed Big Sal. It was all she could say.
Finally, when she had lifted Little Crotchet to his saddle (which was
easy enough to do, he was so small and frail) and returned, Uncle
Turin, foreman of the hoe hands, remarked:—
"You'll be feelin' mighty biggity now, I speck."
"Who? Me?" cried Big Sal. "God knows, I feel so little an' mean I
could t'ar my ha'r out by de han'ful."
Uncle Turin, simple and kindly old soul, never knew then nor later
what Big Sal meant, but ever afterwards, whenever the woman had
one of her tantrums, she went straight to her Little Master, and if
she sometimes came away from him crying it was not his fault. If
she was crying it was because she was comforted, and it all seemed
so simple and natural to her that she never failed to express a deep
desire to tear her hair out if anybody asked her where she had been
or where she was going.
It was not such an easy matter to reach the plow hands. The fields
were wide and the furrows were long on that plantation, and some
of the mules were nimbler than the others, and some of the hands
were quicker. So that it rarely happened that they all came down the
furrows abreast. But what difference did that make? Let them come
one by one, or two by two, or twenty abreast, it was all the same
when the Little Master was in sight. It was hats off and "howdy,"
with "Gee, Beck!" and "Haw, Rhody!" and "Whar you been, Little
Marster, dat we ain't seed you sence day 'fo' yistiddy?" And so until
they had all saluted the child on the Gray Pony.
And why did Susy's Sam hang back and want to turn his mule
around before he had finished the furrow? It was easy to see. Susy's
Sam, though he was the most expert plowman in the gang, had only
one good hand, the other being a mere stump, and he disliked to be
singled out from the rest on that account. But it was useless for him
to hang back. Little Crotchet always called for Susy's Sam.
Sometimes Sam would say that his mule was frisky and wouldn't
stand. But the word would come, "Well, drive the mule out in the
bushes," and then Susy's Sam would have a long resting spell that
did him good, and there would be nobody to complain. And so it was
with the rest. Whoever was sick or tired was sure to catch the Little
Master's eye. How did he know? Well, don't ask too many questions
about that. You might ask how the Gray Pony knew the poison vines
and grasses. It was a case of just knowing, without knowing where
the knowledge came from.
But it was not only the plow hands and the hoe hands that Little
Crotchet knew about. At the close of summer there were the cotton
pickers and the reapers to be looked after. In fact, this was Little
Crotchet's busiest time, for many of the negro children were set to
picking cotton, and the lad felt called on to look after these more
carefully than he looked after the grown hands. Many a time he had
half a dozen holding the Gray Pony at once. This made the older
negroes shake their heads, and say that the Little Master was
spoiling the children, but you may be sure that they thought none
the less of him on that account.
THAT'S RANDALL'S SONG
And then there were the reapers, the men who cut the oats and the
wheat, and the binders that followed after. At the head of the
reapers was Randall, tall, black, and powerful. It was fun to see the
blade of his cradle flashing in the sun, and hear it swing with a swish
through the golden grain. He led the reapers always by many yards,
but when he was making the pace too hot for them he had a way of
stopping to sharpen his scythe and starting up a song which spread
from mouth to mouth until it could be heard for miles. Aaron, hiding
in the wildwoods, could hear it, and at such times he would turn to
one of his companions—the White Pig, or Rambler, or that gay joker,
the Fox Squirrel—and say: "That's Randall's song. He sees the Little
Master coming."
The White Pig would grunt, and Rambler would say he'd rather hear
a horn; but the Red Squirrel would chatter like mad and declare that
he lost one of his ears by sitting on a limb of the live oak and singing
when he saw a man coming.
But the reapers knew nothing about the experience of the Fox
Squirrel, and so they went on singing whenever Randall gave the
word. And Little Crotchet was glad to hear them, for he used to sit
on the Gray Pony and listen, sometimes feeling happy, and at other
times feeling lonely indeed. It may have been the quaint melody that
gave him a lonely feeling, or it may have been his sympathy for
those who suffer the pains of disease or the pangs of trouble. The
negroes used to watch him as they sang and worked, and say in the
pauses of their song:—
"Little marster mighty funny!"
That was the word,—"funny,"—and yet it had a deeper meaning for
the negroes than the white people ever gave it. Funny!—when the
lad leaned his pale cheek on the frail hand, and allowed his thoughts
(were they thoughts or fleeting aspirations or momentary longings?)
to follow the swift, sweet echoes of the song. For the echoes had a
thousand nimble feet, and with these they fled away, away,—away
beyond the river and its bordering hills; for the echoes had
twangling wings, like those of a turtle-dove, and on these they lifted
themselves heavenward, and floated above the world, and above the
toil and trouble and sorrow and pain that dwell therein.
Funny!—when the voice of some singer, sweeter and more powerful
than the rest, rose suddenly from the pauses of the song, and gave
words, as it seemed, to all the suffering that the Little Master had
ever known. Aye! so funny that at such times Little Crotchet would
suddenly wave his hand to the singing reapers, and turn the Gray
Pony's head toward the river. Was he following the rolling echoes?
He could never hope to overtake them.
Once when this happened Uncle Fountain stopped singing to say:—
"I wish I wuz a runaway nigger!"
"No, you don't!" exclaimed Randall.
"Yes, I does," Uncle Fountain insisted.
"How come?"
"Kaze den I'd have little Marster runnin' atter me ev'y chance he
got."
"Go 'way, nigger man! You'd have Jim Simmons's nigger dogs atter
you, an' den what'd you do?"
"Dat ar Aaron had um atter 'im, an' what'd he do?"
"De Lord, He knows,—I don't! But don't you git de consate in yo'
min' dat you kin do what Aaron done done, kaze you'll fool yo'se'f,
sho!"
"What Aaron done done?" Fountain was persistent.
"He done fool dem ar nigger dogs; dat what he done done."
"Den how come I can't fool dem ar dogs?"
"How come? Well, you des try um one time, mo' speshully dat ar
col'-nose dog, which he name Soun'."
"Well, I ain't bleege ter try it when de white folks treat me right,"
remarked Uncle Fountain, after thinking the matter over.
"Dat what make I say what I does," asserted Randall. "When you
know 'zactly what you got, an' when you got mighty nigh what you
want, dat's de time ter lay low an' say nothin'. Hit's some trouble ter
git de corn off'n de cob, but spozen dey want no corn on de cob,
what den?"
"Honey, ain't it de trufe?" exclaimed Uncle Fountain.
Thus the negroes talked. They knew a great deal more about Aaron
than the white people did, but even the negroes didn't know as
much as the Little Master, and for a very good reason. They had no
time to find out things, except at night, and at night—well, you may
believe it or not, just as you please, but at night the door of the
Swamp was closed and locked—locked hard and fast. The owls, the
night hawks, the whippoorwills, and the chuck-will's widows could fly
over. Yes, and the Willis Whistlers could creep through or crawl
under when they returned home from their wild serenades. But
everything else—even that red joker, the Fox Squirrel—must have a
key. Aaron had one, and the White Grunter, and Rambler, and all the
four-footed creatures that walk on horn sandals or in velvet slippers
each had a key. The Little Master might have had one for the asking,
but always when night came he was glad to lie on his sofa and read,
or, better still, go to bed and sleep, so that he never had the need of
a key to open the door of the Swamp after it was closed and locked
at night.
II.
THE SECRETS OF THE SWAMP.

However hard and fast the door of the Swamp may be locked at
night, however tightly it may be shut, it opens quickly enough to
whomsoever carries the key. There is no creaking of its vast and
heavy hinges; there is not the faintest flutter of a leaf, nor the
softest whisper of a blade of grass. That is the bargain the bearer of
the key must make:—

That which sleeps, disturb not its slumber.


That which moves, let it swiftly pass.

Else the Swamp will never reveal itself. The sound of one alien
footfall is enough. It is the signal for each secret to hide itself, and
for all the mysteries to vanish into mystery. The Swamp calls them
all in, covers them as with a mantle, and puts on its every-day
disguise,—the disguise that the eyes of few mortals have ever
penetrated. But those who stand by the bargain that all key-bearers
must make—whether they go on two legs or on four, whether they
fly or crawl or creep or swim—find the Swamp more friendly. There
is no disguise anywhere. The secrets come swarming forth from all
possible or impossible places; and the mysteries, led by their torch-
bearer Jack-o'-the-Lantern, glide through the tall canes and move
about among the tall trees.
The unfathomable blackness of night never sets foot here. It is an
alien and is shut out. And this is one of the mysteries. If, when the
door of the Swamp is opened to a key-bearer the black night seems
to have crept in, wait a moment,—have patience. It is a delusion.
Underneath this leafy covering, in the midst of this dense growth of
vines and saw-grass and reeds and canes, there is always a
wonderful hint of dawn—a shadowy, shimmering hint, elusive and
indescribable, but yet sufficient to give dim shape to that which is
near at hand.
Not far away the frightened squeak of some small bird breaks
sharply on the ear of the Swamp. This is no alien note, and Jack-o'-
the-Lantern dances up and down, and all the mysteries whisper in
concert:—
"We wish you well, Mr. Fox. Don't choke yourself with the feathers.
Good-night, Mr. Fox, good-night!"
Two minute globules of incandescent light come into sight and
disappear, and the mysteries whisper:—
"Too late, Mr. Mink, too late! Better luck next time. Good-night!"
A rippling sound is heard in the lagoon as the Leander of the Swamp
slips into the water. Jack-o'-the-Lantern flits to the level shore of the
pool, and the mysteries come sweeping after, sighing:—
"Farewell, Mr. Muskrat! Good luck and good-night!"
Surely there is an alien sound on the knoll yonder,—snapping,
growling, and fighting. Have stray dogs crept under the door? Oh,
no! The Swamp smiles, and all the mysteries go trooping thither to
see the fun. It is a wonderful frolic! Mr. Red Fox has met Mr. Gray
Fox face to face. Something tells Mr. Red Fox "Here's your father's
enemy." Something whispers to Mr. Gray, "Here's your mother's
murderer." And so they fall to, screaming and gnawing and panting
and snarling. Mr. Gray Fox is the strongest, but his heart is the
weakest. Without warning he turns tail and flies, with Mr. Red Fox
after him, and with all the mysteries keeping them company. They
run until they are past the boundary line,—the place where the
trumpet flower tried to marry the black-jack tree,—and then, of
course, the Swamp has no further concern with them. And the
mysteries and their torch-bearers come trooping home.
MR. RED FOX MEETS MR. GRAY FOX
It is fun when Mr. Red Fox and Mr. Gray Fox meet on the knoll, but
the Swamp will never have such a frolic as it had one night when a
strange bird came flying in over the door. It is known that the birds
that sleep while the Swamp is awake have been taught to hide their
heads under their wings. It is not intended that they should see
what is going on. Even the Buzzard, that sleeps in the loblolly pine,
and the wild turkey, that sleeps in the live oak, conform to this
custom. They are only on the edge of the Swamp, but they feel that
it would be rude not to put their heads under their wings while the
Swamp is awake. But this strange bird—of a family of night birds not
hitherto known to that region—was amazed when he beheld the
spectacle.
"Oho!" he cried; "what queer country is this, where all the birds are
headless? If I'm to live here in peace, I must do as the brethren do."
So he went off in search of advice. As he went along he saw the
Bull-Frog near the lagoon.
"Queerer still," exclaimed the stranger. "Here is a bird that has no
head, and he can sing."
This satisfied him, and he went farther until he saw Mr. Wildcat
trying to catch little Mr. Flying-Squirrel.
"Good-evening, sir," said the stranger. "I see that the birds in this
country have no heads."
Mr. Wildcat smiled and bowed and licked his mouth.
"I presume, sir, that I ought to get rid of my head if I am to stay
here, and I have nowhere else to go. How am I to do it?"
"Easy enough," responded Mr. Wildcat, smiling and bowing and
licking his mouth. "Birds that are so unfortunate as to have heads
frequently come to me for relief. May I examine your neck to see
what can be done?"
The strange bird fully intended to say, "Why, certainly, sir!" He had
the words all made up, but his head was off before he could speak.
Being a large bird, he fluttered and shook his wings and jumped
about a good deal. As the noise was not alien, the Swamp and all its
mysteries came forth to investigate, and oh, what a frolic there was
when Mr. Wildcat related the facts! The torch-bearers danced up and
down with glee, and the mysteries waltzed to the quick piping of the
Willis-Whistlers.
Although the Swamp was not a day older when Aaron, the Son of
Ben Ali, became a key-bearer, the frolic over the headless bird was
far back of Aaron's time. Older! The Swamp was even younger, for it
was not a Swamp until old age had overtaken it—until centuries had
made it fresh and green and strong. The Indians had camped round
about, had tried to run its mysteries down, and had failed. Then
came a band of wandering Spaniards, with ragged clothes, and
tarnished helmets, and rusty shields, and neighing horses—the first
the Swamp had ever seen. The Spaniards floundered in at one side
—where the trumpet vine tried to marry the black-jack tree—and
floundered out on the other side more bedraggled than ever. This
was a great victory for the Swamp, and about that time it came to
know and understand itself. For centuries it had been "organizing,"
and when it pulled De Soto's company of Spaniards in at one side
and flung them out at the other, considerably the worse for wear, it
felt that the "organization" was complete. And so it was and had
been for years and years, and so it remained thereafter—a quiet
place when the sun was above the trees, but wonderfully alert and
alive when night had fallen.
The Swamp that Aaron knew was the same that the Indians and
Spaniards had known. The loblolly pine had grown, and the big
poplars on the knoll had expanded a trifle with the passing
centuries, but otherwise the Swamp was the same. And yet how
different! The Indians had not found it friendly, and the Spaniards
regarded it as an enemy; but to Aaron it gave shelter, and
sometimes food, and its mysteries were his companions. Jack-o'-the-
Lantern showed him the hidden paths when the mists of night fell
darker than usual. He became as much a part of the Swamp as the
mysteries were, entering into its life, and becoming native to all its
moods and conditions. And his presence there seemed to give the
Swamp new responsibilities. Its thousand eyes were always watching
for his enemies, and its thousand tongues were always ready to
whisper the news of the coming of an alien. The turkey buzzard,
soaring thousands of feet above the top of the great pine, the blue
falcon, suspended in the air a mile away, the crow, flapping lazily
across the fields, stood sentinel during the day, and the Swamp
understood the messages they sent. At night the Willis-Whistlers
were on guard, and their lines extended for miles in all directions,
and the Swamp itself was awake, and needed no warning message.
Sometimes at night the sound of Randall's trumpet fell on the ear of
the Swamp, or the voice of Uncle Fountain was heard lifted up in
song, as he went over the hills to his fish-baskets in the river; and
these were restful and pleasing sounds. Sometimes the trailing cry of
hounds was heard. If in the day, Rambler, the track dog, would listen
until he knew whether the cry came from Jim Simmons's "nigger
dogs," from the Gossett hounds, or from some other pack. If at
night, the Swamp cared little about it, for it was used to these things
after the sun went down.
Mr. Coon insisted on gadding about, and it served him right, the
Swamp insisted, when the hounds picked up his drag—as the
huntsmen say—and brought him home with a whirl. He was safe
when he got there, for let the hounds bay at the door of his house
as long as they might, no hunter with torch and axe would venture
into the Swamp. They had tried it—oh, many times.

But the door was locked, and the key


Was safely kid in a hollow tree.

If it was merely Cousin Coon who lived up the river, well and good.
It would teach the incurable vagrant a lesson, and the Swamp
enjoyed the fun. The Willis-Whistlers stopped to listen, the mysteries
hid behind the trees, and Jack-o'-the-Lantern extinguished his torch
as the hounds came nearer with their quavering cries. Was it Mr.
Coon or Cousin Coon? Why, Cousin Coon, of course. How did the
Swamp know? It was the simplest thing in the world. Wasn't there a
splash and a splutter as he ran into the quagmire? Wasn't there a
snap and a snarl when the partridge-pea vine caught his foot? Did
he know the paths? Didn't he double and turn and go back the way
he came, to be caught and killed on dry land? Would Mr. Coon of the
Swamp ever be caught on dry land? Don't you believe it! If cut off
from home, he would run to the nearest pond and plunge in. Once
there, was there a hound that would venture to take a bath with
him? The Swamp laughed at the thought of such a thing. Aaron
smiled, the White Pig grunted, and Rambler grinned. Cousin Coon is
no more, but Mr. Coon is safe at home and the Swamp knows it.

Good luck to all who know the way,


By crooked path and clinging vine!
For them Night's messengers shall stay,
For them the laggard moon shall shine.

But it was not always that aliens and strangers were unwelcome.
Occasionally in the still hours between midnight and dawn the
Swamp would open its doors to Gossett's Riley. He had no key and
he had never come to know and feel that the Swamp was something
more than a mixture of mud and water, trees, canes, vines, and all
manner of flying, creeping, and crawling things. To him the Swamp
was merely a place and not a Thing, but this was ignorance, and the
Swamp forgave it for various reasons, forgave it and pitied him as he
deserved to be pitied. And yet he had qualities out of the common,
and for these the Swamp admired him. He was little more than a
dwarf, being "bow-legged and chuckle-headed," as Susy's Sam used
to say, and was called Chunky Riley, but he was very much of a man
for all that. At a log-rolling there was not a negro for miles around
who could pull him down with the handstick. Aaron could do it, but
Aaron was not a negro, but an Arab, and that is different. Chunky
Riley was even stronger in limb and body than Aaron, but Aaron
used his head, as well as body and limb—and that also is different.
Riley was not swift of foot, but he could run far, as Gossett's hounds
well knew. More than that, he could go on all-fours almost as fast as
he could run on two legs, and that was something difficult to do.
The Swamp found Chunky Riley out in a very curious way. The first
time he came to bring a message to Aaron he waited for no
introduction whatever. The Willis-Whistlers warned him, but he paid
no attention to their warning; the mysteries whispered to him, but
his ears were closed. He searched for no path, and was blind to all
the signals. He blundered into the Swamp and floundered toward
the knoll as the Spaniards did. He floundered out of the quagmire
near where the White Pig lay. He had the scent and all the signs of
an alien, and the White Grunter rushed at him with open mouth. The
Swamp was now angry from centre to circumference, and poor
Chunky Riley's ending would have been swift and sudden but for the
fact that he bore some undeveloped kinship to the elements that
surrounded him.
A-STRADDLE OF THE GRUNTER'S BACK
As the White Pig rushed forward with open mouth, Chunky Riley
caught a vague glimpse of him in the darkness, gave one wild yell,
leaped into the air, and came down a-straddle of the Grunter's back.
This was more than the White Pig had bargained for. He answered
Riley's yell with a loud squeal, and went tearing through the swamp
to the place where Aaron dwelt. The big owl hooted, Rambler
howled, and Jack-o'-the-Lantern threw down his torch and fled. The
Swamp that had been angry was amazed and frightened. What
demon was this that had seized the White Grunter and was carrying
him off? What could the rest hope for if so fierce a creature as the
White Pig could be disposed of in this fashion? Even Aaron was
alarmed at the uproar, for Chunky Riley continued to yell, and the
White Pig kept up its squealing.
It was well that the Grunter, when he came to Aaron's place, ran
close enough to a tree to rub Chunky Riley off his back, otherwise
there is no telling what would have happened. It was well, too, that
Chunky Riley called loudly for Aaron when he fell, otherwise he
would have been made mincemeat of; for as soon as the White Pig
was relieved of his strange burden, his anger rose fiercer than ever,
and he came charging at Chunky Riley, who was lying prone on the
ground, too frightened to do anything more than try to run to a tree
on all-fours. Aaron spoke sharply to the White Pig.
"Shall I use a club on you, White Grunter? Shall I make bacon of
you? You heard him call my name."
The White Pig paused. His small eyes glittered in the dark, and
Chunky Riley heard his tusks grate ominously. He knew the creature
was foaming with rage.
"Ooft! Your name, Son of Ben Ali?" said the White Pig in language
that Chunky Riley thought was merely a series of angry grunts and
snorts. "Ooft! I heard him call for Aaron, and how long has it been
since I heard you say to the Red Chatterer in the hickory-tree that
there were a thousand Aarons, but only one Son of Ben Ali? Ooft-
Gooft! Am I a horse to be ridden? Humph! No man could ride me—it
is what you call a Thing. Umph! let it ride you and then talk about
clubs. Ooft!"
"Is dat Aaron?" Chunky Riley ventured to inquire. "Ef 't is, I wish
you'd be good enough ter run dat ar creetur 'way fum here, kaze I
ain't got no knack fer bein' chaw'd up an' spit out, an' trompled on,
an' teetotally ruint right 'fo' my own face."
"What's your name?" inquired Aaron.
"You ought ter know me, but I dunner whedder you does er not. I'm
name Riley—dey calls me Chunky Riley fer short."
Aaron was silent for a moment, as if trying to remember the name.
Presently he laughed and said: "Why, yes; I know you pretty well.
Come, we'll kindle a fire."
"No suh—not me! Not less'n you'll run dat ar wil' hog off. He mo'
servigrous dan a pant'er. Ef I hadn't er straddled 'im des now he'd 'a'
e't me bodaciously up an' dey wouldn't 'a' been nothin' lef' but de
buttons on my cloze, an' nobody in de roun' worl' would 'a' know'd
dey wuz buttons."
Aaron laughed while speaking to the White Pig: "Get to bed, Grunter.
It is the Lifter—the man that is as strong in the back as a horse."
"Gooft-ooft! Let him ride you out as he rode me in—ooft! He's no
man! Gooft! No bed for me. When a horse is ridden, he must eat, as
I've heard you say, Son of Ben Ali. Gooft-ooft!"
The White Pig, still grinding his tusks together, turned and trotted off
into the darkness, and presently Aaron and Chunky Riley heard him
crashing through the canes and reeds. Then Aaron kindled his fire.
"Why did you come?" inquired the Son of Ben Ali when the two had
made themselves comfortable.
"Des ter fetch word dat Marster wuz layin' off ter git atter you wid
Simmons's nigger-dogs 'fo' long."
"All the way through the dark for that? When did you come to like
me so well?"
"Oh, 't ain't 'zackly dat," replied Chunky Riley frankly. "I hear um
talkin' 'bout it when marster an' dat ar Mr. Simmons wuz walkin' out
in de hoss lot. I wuz in de corn crib, an' dey didn't know it, an' I des
sot dar an' lis'n at um. An' den dis mornin' I seed dat ar little Marse
Abercrombie, an' he say, 'Go tell Aaron quick ez you kin.'"
"The child with the crutches?" queried Aaron.
"De ve'y same," replied Chunky Riley. He paused awhile and then
added: "I'd walk many a long mile fer dat white chil', day er night,
rain er shine."
He gazed in the flickering fire a long time, waiting for Aaron to make
some comment. Hearing none, he finally turned his eyes on his
companion. Aaron was looking skyward, where one small star could
be seen twinkling through the ascending smoke from the fire, and
his lips were moving, though they framed no words that Chunky
Riley could hear. Something in the attitude of the Son of Ben Ali
disturbed the negro.
"Well, I done what I come ter do," he said, making a pretense of
stretching himself and yawning, "an' I speck I'd better be gwine."
The Son of Ben Ali still kept his eye fixed on the twinkling star.
"What pesters me," Chunky Riley went on, "is de idee dat dat ar wil'
hog went 'zackly de way I got ter go. I don't want ter hatter ride 'im
no mo' less'n I got a saddle an' bridle."
"Come!" exclaimed Aaron suddenly, "I'll go with you. I want to see
the Little Master."
"De dogs'll fin' yo' track sho, ef dey start out to-morrer," suggested
Chunky Riley.
The only response the Son of Ben Ali made to this suggestion was to
say: "Take the end of my cane in your hand and follow it. We'll take
a short cut."
Chunky Riley had queer thoughts as he followed his tall conductor,
being led as if he were a blind man; but he said nothing. Presently
(it seemed but a few minutes to Chunky Riley) they stood on the top
of a hill.
"Look yonder!" said Aaron. Away to the left a red light glimmered
faintly.
"What dat?" asked the superstitious negro.
"The light in the Little Master's window."
"How came it so red, den?" inquired Chunky Riley.
"Red curtain," replied Aaron curtly.
"Well, de Lord he'p us! Is we dat close?" cried Chunky Riley.
"Your way is there," said the Son of Ben Ali; "this is mine."
The negro stood watching Aaron until his tall form was lost in the
darkness.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like