Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (3 votes)
42 views

Functional Python Programming Discover the power of functional programming generator functions lazy evaluation the built in itertools library and monads 2nd Edition Steven F. Lott all chapter instant download

library

Uploaded by

jiggsgeteau
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
42 views

Functional Python Programming Discover the power of functional programming generator functions lazy evaluation the built in itertools library and monads 2nd Edition Steven F. Lott all chapter instant download

library

Uploaded by

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

Download the full version of the textbook now at textbookfull.

com

Functional Python Programming Discover the


power of functional programming generator
functions lazy evaluation the built in
itertools library and monads 2nd Edition
Steven F. Lott
https://textbookfull.com/product/functional-
python-programming-discover-the-power-of-
functional-programming-generator-functions-lazy-
evaluation-the-built-in-itertools-library-and-
monads-2nd-edition-steven-f-lott/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Function Python programming discover the power of


functional programming generator functions lazy evaluation
the built in itertools library and monads Second Edition
Lott
https://textbookfull.com/product/function-python-programming-discover-
the-power-of-functional-programming-generator-functions-lazy-
evaluation-the-built-in-itertools-library-and-monads-second-edition-
lott/
textbookfull.com

Functional Python Programming: Use a functional approach


to write succinct, expressive, and efficient Python code,
3rd Edition Lott
https://textbookfull.com/product/functional-python-programming-use-a-
functional-approach-to-write-succinct-expressive-and-efficient-python-
code-3rd-edition-lott/
textbookfull.com

Beginning Functional JavaScript: Uncover the Concepts of


Functional Programming with EcmaScript 8 2nd Edition
Srikanth Machiraju
https://textbookfull.com/product/beginning-functional-javascript-
uncover-the-concepts-of-functional-programming-with-ecmascript-8-2nd-
edition-srikanth-machiraju/
textbookfull.com

Business Cycle Dynamics and Stabilization Policies A


Keynesian Approach 1st Edition Hajime Hori (Auth.)

https://textbookfull.com/product/business-cycle-dynamics-and-
stabilization-policies-a-keynesian-approach-1st-edition-hajime-hori-
auth/
textbookfull.com
Paperback Therapy: Therapist-approved tools and advice for
mastering your mental health 1st Edition Tammi Miller

https://textbookfull.com/product/paperback-therapy-therapist-approved-
tools-and-advice-for-mastering-your-mental-health-1st-edition-tammi-
miller/
textbookfull.com

Finding Places The Search for the Brain s Gps 1st Edition
Unni Eikeseth

https://textbookfull.com/product/finding-places-the-search-for-the-
brain-s-gps-1st-edition-unni-eikeseth/

textbookfull.com

The Morals Of The Market Human Rights And The Rise Of


Neoliberalism Jessica Whyte

https://textbookfull.com/product/the-morals-of-the-market-human-
rights-and-the-rise-of-neoliberalism-jessica-whyte/

textbookfull.com

Identification and Quantification of Drugs, Metabolites,


Drug Metabolizing Enzymes, and Transporters: Concepts,
Methods and Translational Sciences 2nd Edition Shuguang Ma
(Editor)
https://textbookfull.com/product/identification-and-quantification-of-
drugs-metabolites-drug-metabolizing-enzymes-and-transporters-concepts-
methods-and-translational-sciences-2nd-edition-shuguang-ma-editor/
textbookfull.com

Control Systems and Transients For Competitive exams 1st


Edition Rony Parvez

https://textbookfull.com/product/control-systems-and-transients-for-
competitive-exams-1st-edition-rony-parvez/

textbookfull.com
NFPA 70 National Electrical Code 1st Edition Coll.

https://textbookfull.com/product/nfpa-70-national-electrical-code-1st-
edition-coll/

textbookfull.com
Functional Python
Programming
Second Edition

%JTDPWFSUIFQPXFSPGGVODUJPOBMQSPHSBNNJOHHFOFSBUPS
GVODUJPOTMB[ZFWBMVBUJPOUIFCVJMUJOJUFSUPPMTMJCSBSZBOE
NPOBET

Steven F. Lott

BIRMINGHAM - MUMBAI
Functional Python Programming
Second Edition
Copyright a 2018 Packt Publishing

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

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to
have been 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.

Commissioning Editor: Merint Methew


Acquisition Editor: Sandeep Mishra
Content Development Editor: Priyanka Sawant
Technical Editor: Ketan Kamble
Copy Editor: Safis Editing
Project Coordinator: Vaidehi Sawant
Proofreader: Safis Editing
Indexer: Mariammal Chettiyar
Graphics: Jason Monteiro
Production Coordinator: Deepika Naik

First published: January 2015


Second edition: April 2018

Production reference: 1120418

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-78862-706-1

XXXQBDLUQVCDPN
NBQUJP

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as
well as industry leading tools to help you plan your personal development and advance
your career. For more information, please visit our website.

Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos
from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

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 XXX1BDLU1VCDPN and as a
print book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at TFSWJDF!QBDLUQVCDPN for more details.

At XXX1BDLU1VCDPN, 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.
About the author
Steven F. Lott has been programming since the '70s, when computers were large,
expensive, and rare. He's been using Python to solve business problems for over 10 years.
His other titles with Packt Publishing include Python Essentials, Mastering Object-Oriented
Python, Functional Python Programming, and Python for Secret Agents. Steven is currently a
technomad who lives in city along the east coast of the U.S. You can follow his technology
blog (slott-softwarearchitect).
About the reviewer
Yogendra Sharma is a developer with experience in architecture, design, and development
of scalable and distributed applications. He was awarded a bachelorbs degree from the
Rajasthan Technical University in computer science. With a core interest in microservices
and Spring, he also has hands-on experience in technologies such as AWS Cloud, Python,
J2EE, NodeJS, JavaScript, Angular, MongoDB, and Docker.

Currently, he works as an IoT and Cloud Architect at Intelizign Engineering Services Pune.

Packt is searching for authors like you


If you're interested in becoming an author for Packt, please visit BVUIPSTQBDLUQVCDPN and
apply today. We have worked with thousands of developers and tech professionals, just
like you, to help them share their insight with the global tech community. You can make a
general application, apply for a specific hot topic that we are recruiting an author for, or
submit your own idea.
Table of Contents
Copyright and Credits 3
Preface 1
Chapter 1: Understanding Functional Programming 8
Identifying a paradigm 9
Subdividing the procedural paradigm 10
Using the functional paradigm 11
Using a functional hybrid 14
Looking at object creation 15
The stack of turtles 16
A classic example of functional programming 17
Exploratory data analysis 20
Summary 21
Chapter 2: Introducing Essential Functional Concepts 22
First-class functions 23
Pure functions 23
Higher-order functions 24
Immutable data 25
Strict and non-strict evaluation 27
Recursion instead of an explicit loop state 29
Functional type systems 33
Familiar territory 33
Learning some advanced concepts 34
Summary 35
Chapter 3: Functions, Iterators, and Generators 36
Writing pure functions 37
Functions as first-class objects 39
Using strings 41
Using tuples and named tuples 42
Using generator expressions 44
Exploring the limitations of generators 46
Combining generator expressions 48
Cleaning raw data with generator functions 49
Using lists, dicts, and sets 50
Using stateful mappings 54
Using the bisect module to create a mapping 56
Using stateful sets 58
Table of Contents

Summary 58
Chapter 4: Working with Collections 60
An overview of function varieties 61
Working with iterables 61
Parsing an XML file 63
Parsing a file at a higher level 65
Pairing up items from a sequence 67
Using the iter() function explicitly 70
Extending a simple loop 71
Applying generator expressions to scalar functions 74
Using any() and all() as reductions 76
Using len() and sum() 79
Using sums and counts for statistics 79
Using zip() to structure and flatten sequences 82
Unzipping a zipped sequence 84
Flattening sequences 84
Structuring flat sequences 86
Structuring flat sequences – an alternative approach 88
Using reversed() to change the order 89
Using enumerate() to include a sequence number 90
Summary 91
Chapter 5: Higher-Order Functions 92
Using max() and min() to find extrema 93
Using Python lambda forms 97
Lambdas and the lambda calculus 98
Using the map() function to apply a function to a collection 99
Working with lambda forms and map() 100
Using map() with multiple sequences 101
Using the filter() function to pass or reject data 103
Using filter() to identify outliers 104
The iter() function with a sentinel value 105
Using sorted() to put data in order 106
Writing higher-order functions 108
Writing higher-order mappings and filters 108
Unwrapping data while mapping 110
Wrapping additional data while mapping 112
Flattening data while mapping 114
Structuring data while filtering 116
Writing generator functions 117
Building higher-order functions with callables 120
Assuring good functional design 121
Review of some design patterns 123

[ ii ]
Table of Contents

Summary 124
Chapter 6: Recursions and Reductions 126
Simple numerical recursions 127
Implementing tail-call optimization 128
Leaving recursion in place 129
Handling difficult tail-call optimization 130
Processing collections through recursion 131
Tail-call optimization for collections 132
Reductions and folding a collection from many items to one 134
Group-by reduction from many items to fewer 136
Building a mapping with Counter 137
Building a mapping by sorting 138
Grouping or partitioning data by key values 140
Writing more general group-by reductions 143
Writing higher-order reductions 144
Writing file parsers 146
Parsing CSV files 148
Parsing plain text files with headers 150
Summary 153
Chapter 7: Additional Tuple Techniques 154
Using tuples to collect data 155
Using named tuples to collect data 157
Building named tuples with functional constructors 160
Avoiding stateful classes by using families of tuples 161
Assigning statistical ranks 165
Wrapping instead of state changing 167
Rewrapping instead of state changing 168
Computing Spearman rank-order correlation 170
Polymorphism and type-pattern matching 171
Summary 178
Chapter 8: The Itertools Module 179
Working with the infinite iterators 180
Counting with count() 181
Counting with float arguments 182
Re-iterating a cycle with cycle() 184
Repeating a single value with repeat() 186
Using the finite iterators 187
Assigning numbers with enumerate() 188
Running totals with accumulate() 190
Combining iterators with chain() 191
Partitioning an iterator with groupby() 192
Merging iterables with zip_longest() and zip() 194
Filtering with compress() 194

[ iii ]
Table of Contents

Picking subsets with islice() 196


Stateful filtering with dropwhile() and takewhile() 197
Two approaches to filtering with filterfalse() and filter() 198
Applying a function to data via starmap() and map() 199
Cloning iterators with tee() 201
The itertools recipes 201
Summary 203
Chapter 9: More Itertools Techniques 205
Enumerating the Cartesian product 206
Reducing a product 206
Computing distances 208
Getting all pixels and all colors 210
Performance analysis 212
Rearranging the problem 214
Combining two transformations 215
Permuting a collection of values 216
Generating all combinations 218
Recipes 220
Summary 221
Chapter 10: The Functools Module 222
Function tools 223
Memoizing previous results with lru_cache 223
Defining classes with total ordering 225
Defining number classes 228
Applying partial arguments with partial() 230
Reducing sets of data with the reduce() function 231
Combining map() and reduce() 232
Using the reduce() and partial() functions 234
Using the map() and reduce() functions to sanitize raw data 235
Using the groupby() and reduce() functions 236
Summary 239
Chapter 11: Decorator Design Techniques 241
Decorators as higher-order functions 241
Using the functools update_wrapper() functions 246
Cross-cutting concerns 246
Composite design 247
Preprocessing bad data 249
Adding a parameter to a decorator 251
Implementing more complex decorators 253
Complex design considerations 254
Summary 258

[ iv ]
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents

Chapter 12: The Multiprocessing and Threading Modules 259


Functional programming and concurrency 260
What concurrency really means 261
The boundary conditions 261
Sharing resources with process or threads 262
Where benefits will accrue 263
Using multiprocessing pools and tasks 264
Processing many large files 264
Parsing log files – gathering the rows 266
Parsing log lines into namedtuples 267
Parsing additional fields of an Access object 270
Filtering the access details 273
Analyzing the access details 275
The complete analysis process 276
Using a multiprocessing pool for concurrent processing 277
Using apply() to make a single request 280
Using the map_async(), starmap_async(), and apply_async() functions 280
More complex multiprocessing architectures 281
Using the concurrent.futures module 282
Using concurrent.futures thread pools 282
Using the threading and queue modules 283
Designing concurrent processing 284
Summary 286
Chapter 13: Conditional Expressions and the Operator Module 287
Evaluating conditional expressions 288
Exploiting non-strict dictionary rules 289
Filtering true conditional expressions 291
Finding a matching pattern 292
Using the operator module instead of lambdas 293
Getting named attributes when using higher-order functions 295
Starmapping with operators 296
Reducing with operator module functions 298
Summary 299
Chapter 14: The PyMonad Library 301
Downloading and installing 301
Functional composition and currying 302
Using curried higher-order functions 304
Currying the hard way 306
Functional composition and the PyMonad * operator 307
Functors and applicative functors 308
Using the lazy List() functor 310
Monad bind() function and the >> operator 313
Implementing simulation with monads 314

[v]
Table of Contents

Additional PyMonad features 318


Summary 319
Chapter 15: A Functional Approach to Web Services 320
The HTTP request-response model 321
Injecting state through cookies 323
Considering a server with a functional design 324
Looking more deeply into the functional view 324
Nesting the services 325
The WSGI standard 326
Throwing exceptions during WSGI processing 329
Pragmatic WSGI applications 331
Defining web services as functions 331
Creating the WSGI application 332
Getting raw data 335
Applying a filter 337
Serializing the results 337
Serializing data into JSON or CSV formats 339
Serializing data into XML 340
Serializing data into HTML 341
Tracking usage 343
Summary 344
Chapter 16: Optimizations and Improvements 346
Memoization and caching 347
Specializing memoization 348
Tail recursion optimizations 350
Optimizing storage 352
Optimizing accuracy 353
Reducing accuracy based on audience requirements 353
Case study–making a chi-squared decision 354
Filtering and reducing the raw data with a Counter object 355
Reading summarized data 357
Computing sums with a Counter object 358
Computing probabilities from Counter objects 360
Computing expected values and displaying a contingency table 361
Computing the chi-squared value 363
Computing the chi-squared threshold 364
Computing the incomplete gamma function 365
Computing the complete gamma function 368
Computing the odds of a distribution being random 369
Functional programming design patterns 371
Summary 373
Other Books You May Enjoy 375

[ vi ]
Table of Contents

Index 378

[ vii ]
Preface
Functional programming offers a variety of techniques for creating succinct and expressive
software. While Python is not a purely functional programming language, we can do a
great deal of functional programming in Python.

Python has a core set of functional programming features. This lets us borrow many design
patterns and techniques from other functional languages. These borrowed concepts can lead
us to create succinct and elegant programs. Python's generator expressions, in particular,
negate the need to create large in-memory data structures, leading to programs that may
execute more quickly because they use fewer resources.

We canbt easily create purely functional programs in Python. Python lacks a number of
features that would be required for this. We donbt have unlimited recursion, for example,
we donbt have lazy evaluation of all expressions, and we donbt have an optimizing compiler.

There are several key features of functional programming languages that are available in
Python. One of the most important ones is the idea of functions being first-class
objects. Python also offers a number of higher-order functions. The built-in NBQ ,
GJMUFS , and GVODUPPMTSFEVDF functions are widely used in this role, and less-
obvious are functions such as TPSUFE , NJO , and NBY .

Webll look at the core features of functional programming from a Python point of view. Our
objective is to borrow good ideas from functional programming languages and use those
ideas to create expressive and succinct applications in Python.

Who this book is for


This book is for programmers who want to create succinct, expressive Python programs by
borrowing techniques and design patterns from functional programming languages. Some
algorithms can be expressed elegantly in a functional style; we cancand shouldcadapt
this to make Python programs more readable and maintainable.

In some cases, a functional approach to a problem will also lead to extremely high-
performance algorithms. Python makes it too easy to create large intermediate data
structures, tying up memory (and processor time.) With functional programming design
patterns, we can often replace large lists with generator expressions that are equally
expressive but take up much less memory and run much more quickly.
Preface

What this book covers


$IBQUFS, Understanding Functional Programming, introduces some of the techniques that
characterize functional programming. Webll identify some of the ways to map those features
to Python. Finally, webll also address some ways that the benefits of functional
programming accrue when we use these design patterns to build Python applications.

$IBQUFS, Introducing Essential Functional Concepts, delves into six central features of the
functional programming paradigm. Webll look at each in some detail to see how theybre
implemented in Python. Webll also point out some features of functional languages that
donbt apply well to Python. In particular, many functional languages have complex type-
matching rules required to support compiling and optimizing.

$IBQUFS, Functions, Iterators, and Generators, will show how to leverage immutable Python
objects, and generator expressions adapt functional programming concepts to the Python
language. Webll look at some of the built-in Python collections and how we can leverage
them without departing too far from functional programming concepts.

$IBQUFS, Working with Collections, shows how you can use a number of built-in Python
functions to operate on collections of data. This chapter will focus on a number of relatively
simple functions, such as BOZ and BMM , which will reduce a collection of values to a
single result.

$IBQUFS, Higher-Order Functions, examines the commonly-used higher-order functions


such as NBQ and GJMUFS . It also shows a number of other functions that are also
higher-order functions as well as how we can create our own higher-order functions.

$IBQUFS, Recursions and Reductions, teaches how to design an algorithm using recursion
and then optimize it into a high-performance GPS loop. Webll also look at some other
reductions that are widely used, including DPMMFDUJPOT$PVOUFS .

$IBQUFS, Additional Tuple Techniques, showcases a number of ways that we can use
immutable tuples (and namedtuples) instead of stateful objects. Immutable objects have a
much simpler interfacecwe never have to worry about abusing an attribute and setting an
object into some inconsistent or invalid state.

$IBQUFS, The Itertools Module, examines a number of functions in this standard library
module. This collection of functions simplifies writing programs that deal with collections
or generator functions.

[2]
Preface

$IBQUFS, More Itertools Techniques, covers the combinatoric functions in the itertools
module. These functions are somewhat less useful. This chapter includes some examples
that illustrate ill-considered use of these functions and the consequences of combinatoric
explosion.

$IBQUFS, The Functools Module, focuses on how to use some of the functions in this
module for functional programming. A few functions in this module are more appropriate
for building decorators, and they are left for $IBQUFS, Decorator Design Techniques. The
other functions, however, provide several more ways to design and implement function
programs.

$IBQUFS, Decorator Design Techniques, looks at how you can look at a decorator as a way
to build a composite function. While there is considerable flexibility here, there are also
some conceptual limitations: webll look at ways that overly-complex decorators can become
confusing rather than helpful.

$IBQUFS, The Multiprocessing and Threading Modules, points out an important


consequence of good functional design: we can distribute the processing workload. Using
immutable objects means that we canbt corrupt an object because of poorly-synchronized
write operations.

$IBQUFS, Conditional Expressions and the Operator Module, lists some ways to break out of
Pythonbs strict order of evaluation. There are limitations to what we can achieve here. Webll
also look at the operator module and how this can lead to slight clarification of some simple
kinds of processing.

$IBQUFS, The PyMonad Library, examines some of the features of the PyMonad library.
This provides some additional functional programming features. It also provides a way to
learn more about monads. In some functional languages, monads are an important way to
force a particular order for operations that might get optimized into an undesirable order.
Since Python already has strict ordering of f expressions and statements, the monad feature
is more instructive than practical.

$IBQUFS, A Functional Approach to Web Services, shows how we can think of web services
as a nested collection of functions that transform a request into a reply. Webll see ways to
leverage functional programming concepts for building responsive, dynamic web content.

$IBQUFS, Optimizations and Improvements, includes some additional tips on performance


and optimization. Webll emphasize techniques such as memoization, because theybre easy to
implement and cancin the right contextcyield dramatic performance improvements.

[3]
Preface

To get the most out of this book


This book presumes some familiarity with Python 3 and general concepts of application
development. We wonbt look deeply at subtle or complex features of Python; webll avoid
much consideration of the internals of the language.

Webll presume some familiarity with functional programming. Since Python is not a
functional programming language, we canbt dig deeply into functional concepts. Webll pick
and choose the aspects of functional programming that fit well with Python and leverage
just those that seem useful.

Some of the examples use exploratory data analysis (EDA) as a problem domain to show
the value of functional programming. Some familiarity with basic probability and statistics
will help with this. There are only a few examples that move into more serious data science.

Youbll need to have Python 3.6 installed and running. For more information on Python, visit
IUUQXXXQZUIPOPSH. The examples all make extensive use of type hints, which means
that the latest version of mypy must be installed as well.

Check out IUUQTQZQJQZUIPOPSHQZQJNZQZ for the latest version of mypy.

Examples in $IBQUFS, More Itertools Techniques, use PIL and Beautiful Soup 4. The Pillow
fork of the original PIL library works nicely; refer to IUUQTQZQJQZUIPOPSHQZQJ
1JMMPX and IUUQTQZQJQZUIPOPSHQZQJCFBVUJGVMTPVQ.

Examples in $IBQUFS, The PyMonad Library, use PyMonad; check out IUUQTQZQJ
QZUIPOPSHQZQJ1Z.POBE.

All of these packages should be installed using the following:


$ pip install pillow beautifulsoup4 PyMonad

Download the example code files


You can download the example code files for this book from your account at
XXXQBDLUQVCDPN. If you purchased this book elsewhere, you can visit
XXXQBDLUQVCDPNTVQQPSU and register to have the files emailed directly to you.

[4]
Preface

You can download the code files by following these steps:

1. Log in or register at XXXQBDLUQVCDPN.


2. Select the SUPPORT tab.
3. Click on Code Downloads & Errata.
4. Enter the name of the book in the Search box and follow the onscreen
instructions.

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 IUUQTHJUIVCDPN
1BDLU1VCMJTIJOH'VODUJPOBM1ZUIPO1SPHSBNNJOH4FDPOE&EJUJPO. We also have other
code bundles from our rich catalog of books and videos available at IUUQTHJUIVCDPN
1BDLU1VCMJTIJOH. Check them out!

Conventions used
There are a number of text conventions used throughout this book.

$PEF*O5FYU: Indicates code words in text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an
example: "Python has other statements, such as HMPCBM or OPOMPDBM, which modify the
rules for variables in a particular namespace."

[5]
Preface

A block of code is set as follows:


T
GPSOJOSBOHF  
JGOPSO
T O
QSJOU T

When we wish to draw your attention to a particular part of a code block, the relevant lines
or items are set in bold:
T
GPSOJOSBOHF  
JGOPSO
s += n
QSJOU T

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


$ pip install pillow beautifulsoup4 PyMonad

Bold: Indicates a new term, an important word, or words that you see onscreen. For
example, words in menus or dialog boxes appear in the text like this. Here is an example:
"For our purposes, we will distinguish between only two of the many
paradigms: functional programming and imperative programming."

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch
Feedback from our readers is always welcome.

General feedback: Email GFFECBDL!QBDLUQVCDPN and mention the book title in the
subject of your message. If you have questions about any aspect of this book, please email
us at RVFTUJPOT!QBDLUQVCDPN.

[6]
Preface

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you have found a mistake in this book, we would be grateful if you would
report this to us. Please visit XXXQBDLUQVCDPNTVCNJUFSSBUB, selecting your book,
clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we
would be grateful if you would provide us with the location address or website name.
Please contact us at DPQZSJHIU!QBDLUQVCDPN with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in
and you are interested in either writing or contributing to a book, please visit
BVUIPSTQBDLUQVCDPN.

Reviews
Please leave a review. Once you have read and used this book, why not leave a review on
the site that you purchased it from? Potential readers can then see and use your unbiased
opinion to make purchase decisions, we at Packt can understand what you think about our
products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit QBDLUQVCDPN.

[7]
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
1
Understanding Functional
Programming
Functional programming defines a computation using expressions and evaluation; often
these are encapsulated in function definitions. It de-emphasizes or avoids the complexity of
state change and mutable objects. This tends to create programs that are more succinct and
expressive. In this chapter, we'll introduce some of the techniques that characterize
functional programming. We'll identify some of the ways to map these features to Python.
Finally, we'll also address some ways in which the benefits of functional programming
accrue when we use these design patterns to build Python applications.

Python has numerous functional programming features. It is not a purely a functional


programming language. It offers enough of the right kinds of features that it confers the
benefits of functional programming. It also retains all the optimization power of an
imperative programming language.

We'll also look at a problem domain that we'll use for many of the examples in this book.
We'll try to stick closely to Exploratory Data Analysis (EDA) because its algorithms are
often good examples of functional programming. Furthermore, the benefits of functional
programming accrue rapidly in this problem domain.

Our goal is to establish some essential principles of functional programming. The more
serious Python code will begin in $IBQUFS, Introducing Some Functional Features.

We'll focus on Python 3.6 features in this book. However, some of the
examples might also work in Python 2.
Understanding Functional Programming Chapter 1

Identifying a paradigm
It's difficult to be definitive on the universe of programming paradigms. For our purposes,
we will distinguish between only two of the many
paradigms: functional programming and imperative programming. One important
distinguishing feature between these two is the concept of state.

In an imperative language, such as Python, the state of the computation is reflected by the
values of the variables in the various namespaces; some kinds of statements make a well-
defined change to the state by adding or changing (or even removing) a variable. A
language is imperative because each statement is a command, which changes the state
in some way.

Our general focus is on the assignment statement and how it changes the state. Python has
other statements, such as HMPCBM or OPOMPDBM, which modify the rules for variables in a
particular namespace. Statements such as EFG, DMBTT, and JNQPSU change the processing
context. Other statements such as USZ, FYDFQU, JG, FMJG, and FMTF act as guards to modify
how a collection of statements will change the computation's state. Statements such as GPS
and XIJMF, similarly, wrap a block of statements so that the statements can make repeated
changes to the state of the computation. The focus of all these various statement types,
however, is on changing the state of the variables.

Ideally, each assignment statement advances the state of the computation from an initial
condition toward the desired final outcome. This advancing the computation assertion can be
challenging to prove. One approach is to define the final state, identify a statement that will
establish this final state, and then deduce the precondition required for this final statement
to work. This design process can be iterated until an acceptable initial state is derived.

In a functional language, we replace the statecthe changing values of variablescwith a


simpler notion of evaluating functions. Each function evaluation creates a new object or
objects from existing objects. Since a functional program is a composition of functions, we
can design lower-level functions that are easy to understand, and then design higher-level
compositions that can also be easier to visualize than a complex sequence of statements.

Function evaluation more closely parallels mathematical formalisms. Because of this, we


can often use simple algebra to design an algorithm, which clearly handles the edge cases
and boundary conditions. This makes us more confident that the functions work. It also
makes it easy to locate test cases for formal unit testing.

[9]
Understanding Functional Programming Chapter 1

It's important to note that functional programs tend to be relatively succinct, expressive,
and efficient compared to imperative (object-oriented or procedural) programs. The benefit
isn't automatic; it requires a careful design. This design effort for functional programming is
often easier than for procedural programming.

Subdividing the procedural paradigm


We can subdivide imperative languages into a number of discrete categories. In this section,
we'll glance quickly at the procedural versus object-oriented distinction. What's important
here is to see how object-oriented programming is a subset of imperative programming. The
distinction between procedural and object-orientation doesn't reflect the kind of
fundamental difference that functional programming represents.

We'll use code examples to illustrate the concepts. For some, this will feel like reinventing
the wheel. For others, it provides a concrete expression of abstract concepts.

For some kinds of computations, we can ignore Python's object-oriented features and write
simple numeric algorithms. For example, we might write something like the following to
sum a range of numbers that share a common property:
T
GPSOJOSBOHF  
JGOPSO
T O
QSJOU T

The sum T includes only numbers that are multiples of three or five. We've made this
program strictly procedural, avoiding any explicit use of Python's object features. The
program's state is defined by the values of the variables T and O. The variable O takes on
values such that 1 d n < 10. As the loop involves an ordered exploration of values of O, we
can prove that it will terminate when O. Similar code would work in C or Java
language, using their primitive (non-object) data types.

We can exploit Python's Object-Oriented Programming (OOP) features and create a


similar program:
NMJTU
GPSOJOSBOHF  
JGOPSO
NBQQFOE O
QSJOU TVN N

[ 10 ]
Understanding Functional Programming Chapter 1

This program produces the same result but it accumulates a stateful collection object, N, as it
proceeds. The state of the computation is defined by the values of the variables N and O.

The syntax of NBQQFOE O and TVN N can be confusing. It causes some programmers to
insist (wrongly) that Python is somehow not purely object-oriented because it has a mixture
of the GVODUJPO and PCKFDUNFUIPE syntax. Rest assured, Python is purely object-
oriented. Some languages, such as C++, allow the use of primitive data types such as JOU,
GMPBU, and MPOH, which are not objects. Python doesn't have these primitive types. The
presence of prefix syntax, TVN N , doesn't change the nature of the language.

To be pedantic, we could fully embrace the object model, by defining a subclass of the MJTU
class. This new class will include a TVN method:
DMBTT4VNNBCMF@-JTU MJTU 
EFGTVN TFMG 
T
GPSWJOTFMG
T W
SFUVSOT

If we initialize the variable N with an instance of the 4VNNBCMF@-JTU class instead of the
MJTU method, we can use the NTVN method instead of the TVN N method. This kind
of change can help to clarify the idea that Python is truly and completely object-oriented.
The use of prefix function notation is purely syntactic sugar.

All three of these examples rely on variables to explicitly show the state of the program.
They rely on the assignment statements to change the values of the variables and advance
the computation toward completion. We can insert the BTTFSU statements throughout these
examples to demonstrate that the expected state changes are implemented properly.

The point is not that imperative programming is broken in some way. The point is that
functional programming leads to a change in viewpoint, which can, in many cases, be very
helpful. We'll show a function view of the same algorithm. Functional programming doesn't
make this example dramatically shorter or faster.

Using the functional paradigm


In a functional sense, the sum of the multiples of three and five can be defined in two parts:

The sum of a sequence of numbers


A sequence of values that pass a simple test condition, for example, being
multiples of three and five

[ 11 ]
Understanding Functional Programming Chapter 1

The sum of a sequence has a simple, recursive definition:


EFGTVNS TFR 
JGMFO TFR SFUVSO
SFUVSOTFR<> TVNS TFR<>

We've defined the sum of a sequence in two cases: the base case states that the sum of a
zero length sequence is 0, while the recursive case states that the sum of a sequence is the
first value plus the sum of the rest of the sequence. Since the recursive definition depends
on a shorter sequence, we can be sure that it will (eventually) devolve to the base case.

Here are some examples of how this function works:


>>> sumr([7, 11])
18
>>> 7+sumr([11])
18
>>> 18+sumr([])
0

The first example computes the sum of a list with multiple items. The second example
shows how the recursion rule works by adding the first item, TFR<>, to the sum of the
remaining items, TVNS TFR<> . Eventually, the computation of the result involves the
sum of an empty list, which is defined as zero.

The operator on the last line of the preceding example and the initial value of  in the base
case characterize the equation as a sum. If we change the operator to and the initial value
to , it would just as easily compute a product. We'll return to this simple idea of
generalization in the following chapters.

Similarly, a sequence of values can have a simple, recursive definition, as follows:


EFGVOUJM OGJMUFS@GVODW 
JGWOSFUVSO<>
JGGJMUFS@GVOD W SFUVSO<W> VOUJM OGJMUFS@GVODW 
FMTFSFUVSOVOUJM OGJMUFS@GVODW 

In this function, we've compared a given value, W, against the upper bound, O. If W reaches
the upper bound, the resulting list must be empty. This is the base case for the given
recursion.

[ 12 ]
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Tom Swift and
his airline express
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Tom Swift and his airline express


or, From ocean to ocean by daylight

Author: Victor Appleton

Release date: January 13, 2024 [eBook #72701]

Language: English

Original publication: Racine, WI: Whitman Publishing Co, 1926

Credits: Delphine Lettau, Cindy Beyer & the online Distributed


Proofreaders Canada team at http://www.pgdpcanada.net

*** START OF THE PROJECT GUTENBERG EBOOK TOM SWIFT


AND HIS AIRLINE EXPRESS ***
TOM SWIFT AND HIS
AIRLINE EXPRESS
or

From Ocean to Ocean by Daylight

by
VICTOR APPLETON

WHITMAN PUBLISHING CO.


Racine, Wis. Poughkeepsie, N. Y.

Copyright, 1926, by
GROSSET & DUNLAP, Inc.
New York, N. Y.
ALL RIGHTS RESERVED
Printed in U. S. A.

CONTENTS

I. Something Queer
II. Waiting in the Dark
III. Masked Men
IV. A Night of Worry
V. A Crash
VI. Again a Prisoner
VII. The Plot
VIII. Mr. Damon’s News
IX. Koku’s Alarm
X. Tom’s Plight
XI. The Explosion
XII. A Dangerous Search
XIII. An Ominous Message
XIV. The Airline Express
XV. A Trial Flight
XVI. Jason Jacks
XVII. The Airline Starts
XVIII. Chicago
XIX. Denver
XX. A Mountain Storm
XXI. The Golden Gate
XXII. Kenny Breaks Down
XXIII. Another Capture
XXIV. Troubles and Worries
XXV. A Glorious Finish
Tom Swift and His Airline Express
CHAPTER I
SOMETHING QUEER

“Ours is sure a great plant!” murmured Tom Swift to himself, with


justifiable pride. “It would be a credit to anybody. No wonder dad
loves it, and so do I. Yes, it sure is a great plant! We’ve had our
troubles—our ups and downs—and our enemies have tried their
hardest to wipe it out.”
Darkness was slowly gathering over the landscape, shrouding in
velvety black the trees which were faintly stirring in the summer
breeze. Tom, following an old-time cowpath across the green
meadow on his way home from town, topped a little rise and caught
a glimpse of the high board fence surrounding the Swift Construction
Company’s plant which he and his father had built up after many
years of hard work.
Tom paused for a moment to trace, in the fast-gathering shadows
of the night, the outlines of the various buildings—the foundry, the
wood-working mill, the electrical shop, the hangars where many
types of aircraft were housed.
From some of the tall chimneys faint clouds of smoke arose, for
certain of the industries carried on by the Swift Construction
Company required that furnaces be kept going day and night.
“A great plant—a wonderful plant!” mused Tom. It gave him a
certain sense of pleasure to dwell thus in introspection on the
accomplishments of his father and himself. And it buoyed him up for
the work in prospect—for Tom Swift had a great plan in mind, a plan
so great and daring that, as yet, he had said but little of it even to his
father or to Ned Newton, his old chum who was now an officer of the
concern.
“But it can be done! I know it can be done!” declared Tom. “And
I’m going to do it! I’m going to——”
In his mental energy he had unconsciously spoken the last words
in a low voice, but the sight of something just ahead of him in the
gathering darkness caused him to break off abruptly and halt
suddenly. Concentrating his gaze, Tom Swift looked eagerly at a
clump of bushes.
“It’s a man,” murmured Tom Swift. “A man, sure enough, and it
isn’t one of our workers, either. None of them would sneak around as
he is doing.”
For that described exactly the movements of the stranger of
whom Tom had caught sight in the darkness as he approached the
big fence which surrounded his plant.
“What’s he up to?” mused Tom. “No good, that’s sure. He
wouldn’t sneak along like that if he were on the level.”
Through Tom’s mind flashed remembrances of times when
attempts had been made by enemies of himself and his father to fire
the plant. To prevent this, and to keep strangers away, a high fence
had been erected around the buildings. This fence was protected by
wires on the plan of a burglar alarm, so that, no matter at what point
the barrier was climbed, a bell would ring in the main office and on
an indicator would appear a number to show at what part of the
fence an attempt was being made to scale it.
An effort to break down the barrier, or burrow beneath it, would
also sound the alarm in like manner. So Tom had no fear that the
sneaking stranger, crouching along in the darkness, could get into
the midst of the buildings without notice being given.
“But what’s his game?” thought Tom.
Almost at the instant he asked himself this question he saw the
man crawl behind a clump of bushes. In the natural course of events
the man should have appeared on the other side of the clump. But
he did nothing of the sort.
“He may be hiding there,” mused Tom. “Perhaps waiting for a
confederate. I’ll just have a closer look at this!”
He advanced boldly toward the bushes. There was nothing
between him and the shrubbery, and it was still light enough to see
fairly well. Besides, Tom had extraordinarily good eyes. His
astonishment can be imagined when, on reaching the bush off which
he had not taken his gaze and behind which he had seen the
crawling man disappear he found—no one!
“That’s the queerest thing I’ve seen yet!” exclaimed Tom, rubbing
his organs of vision.
Standing beside the bush which came about to his shoulders,
Tom looked on all sides of it. There was no hollow in the ground, as
far as he could make out, no depression and no other clumps of
shrubbery and no boulders behind which a man might be hidden.
Some distance away there were all of these things in profusion, for
the land was wild and uncultivated outside the plant fence. But there
was not a hole, boulder, or bush near enough to the one beside
which Tom stood to have enabled a man to gain their protection
while the young inventor was watching.
“He just crawled back of his bush and then vanished!” said Tom,
in a half whisper to himself. “If only I had a flashlight now——” He
was startled by hearing some one walking toward him out of the
darkness which was now quite dense. “Here he comes!” thought
Tom. “Appearing as queerly as he disappeared. Or else it’s one of
his confederates.” He could see no one, and his hand clutched
something in his pocket that might be used in case he was attacked.
But a moment later, just as Tom’s nerves and muscles were
getting tense in anticipation of a struggle, a cheery whistle broke out
in the darkness, mingling with the now louder sounds of the
footsteps, and Tom, with a cry of relief, called:
“That you, Ned?”
“Sure, old scout!” was the reply. “Oh, there you are!” went on Ned
Newton, as he caught sight of Tom at the same moment the young
inventor glimpsed his friend and financial manager.
“You’re a bit late,” went on Ned. “I waited for you, and when you
didn’t show up I thought I might as well walk in toward town and
maybe I’d meet you.”
“Yes, I couldn’t get just what I wanted until I had tried two or three
places,” Tom answered. “And then I met a man——”
Ned broke into a laugh.
“What’s the idea?” Tom wanted to know.
“Tell that to Mary!” advised his chum. “She may believe that and
then you can tell her another.”
“Whew!” shrilly whistled Tom. “I forgot all about Mary. I promised
to call on her to-night.”
“Sure you did,” laughed Ned. “And I’ve got a date with Helen. You
said we’d go over together and——”
“Clean forgot it!” broke in Tom. “And I can’t go now. I’ve got
something to do.” Quickly he made up his mind to say nothing to
Ned of what he had seen until he investigated a little on his own
account. “Here, I tell you what to do,” went on Tom. “Go on, keep
your date with Helen, but when you get to her house telephone to
Mary for me and say I’ll be a little late. Will you?”
“Pull your chestnuts out of the fire? Is that it, Tom? I reminded
you myself before supper!” laughed Ned. “Well, I don’t mind, for
you’ve done the same for me. I guess Mary Nestor knows you by
this time, or, if she doesn’t, she never will. But what’s the big idea?”
“Oh, I’ve just got a notion in my head,” said Tom. “I want to go to
the office a moment to jot down some memoranda before I forget
them. ’Phone Mary I’ll be over as soon as I can. See you later.”
“Cheek!” exclaimed Ned, and with his merry whistle he hurried off
in the darkness. “I only hope Mary speaks to you when you finally
get to see her,” floated back to Tom.
“Don’t you worry about Mary,” advised the young inventor. “I’ll
explain to her. And tell her I’ll be along in about half an hour. I really
forgot all about the engagement.”
“I’ll say you did!” playfully mocked Ned.
Then, with his chum out of the way, Tom gave himself to trying to
solve the mystery. For mystery he believed it to be. Seeing a man
step behind a bush and, on arriving at the bush, to find nothing of the
man there was surprising, to say the least.
Sensing that it would soon be so dark that it would be useless to
investigate without an illuminant of some sort, Tom made haste to
gain what advantage he could from the fast-fading light. He looked
sharply about without moving from his place behind the bush on the
other side of which he had seen the man disappear. Then, as he
could pick up here no clew to the strange happening, the young
inventor moved around to the other side.
The light was a little better here and Tom saw something that
made him fairly gasp with astonishment. He had moved somewhat
away from the bush and almost at his feet was an opening in the
ground.
“This explains it!” murmured Tom, half aloud. “A hole in the
ground! He went down there. I knew he couldn’t have dug himself in
as quickly as that. But that hole! I never saw it before. It isn’t any of
our doing. I’d have known about it if it were.”
All the land there belonged to Tom and his father. It was a big
field surrounding the fenced-in plant, and often the smooth part of
the field was used as a landing place for aeroplanes.
Cautiously approaching the opening in the ground and wondering
more and more how it had gotten there without his knowledge, Tom
saw that it had been closed by some planks placed over it. These
were now tossed to one side, as if they had been hurriedly
displaced. Scattered about was loose earth which had evidently
covered the planks, thus hiding them from the view of a casual
observer.
“A secret opening!” murmured Tom. “This is certainly the
queerest thing I’ve ever seen! What does it mean?”
His surprise increased when, as he drew near to the edge of the
opening, he saw a rough flight of plank steps going down into the
hole. The young man caught his breath sharply, it was so
astounding. But with Tom Swift to see and think was to act, and a
moment later he began a descent of the steps into the mysterious
hole. It might have been the part of discretion to wait until daylight,
but a secret opening like this, so near the Swift plant, could mean but
one thing, Tom reasoned.
“Some one is trying to put up a game on us,” he decided.
“Unknown to us he has made a tunnel under our plant. There’s
something funny here! I’m going to see what it is.”
Tom had fairly to feel his way down the flight of plank steps. They
were rough and uneven, but solidly built. The young inventor
counted them as he descended so he would know how to come
back. Now that his head was below the level of the ground it was so
dark that it was as if a velvet robe had been wrapped about him.
He counted ten steps down, and was cautiously feeling about
with his right foot extended to ascertain if there were any more, when
suddenly he felt the presence of some one near him. He caught the
sound of breath fiercely drawn in, as if his unknown and unseen
companion, there in the darkness, was nerving himself for an attack.
Instinctively Tom drew back, his hands pressed to the planked
sides of the opening down which he had descended. He could feel,
rather than see, some one leaning toward him. A sweet, sickening
odor came to his nostrils. He felt a hand pressed over his face—a
hand that held a damp rag which gave off that overpowering
perfume.
“Here! What’s this? Who—who——” But Tom Swift’s voice
became a mere gurgle in his throat. His legs became limp. His head
whirled and he seemed lifted up and carried through measureless
miles of space on the wings of some great bird.
Then Tom’s senses left him. He knew no more.
CHAPTER II
WAITING IN THE DARK

Just how long Tom Swift remained unconscious he himself did


not know. It may have been several hours, for when he came to
himself he felt a curious stiffness about his muscles as if he had lain
for some time on the damp ground.
And he was on the ground—a fact he ascertained by feeling
about with his hands, his fingers encountering damp, packed earth
and the smooth surface of stones set in the soil.
“Where in the world am I, and what happened?” thought Tom, as
soon as he could collect his senses enough to do any thinking. “Gee,
but I sure do feel queer!”
There was a sickish taste in his mouth—a sense of sweetness,
such as he remembered followed a slight operation he had
undergone some years before when an anæsthetic had been given
him.
“They doped me all right—that’s what they did,” mused Tom.
“Ether, chloroform, or something like that. It knocked me out. But I’m
beginning to feel all right again—no headache or anything like that.
But what does it all mean, and where am I?”
Those were questions not easily answered.
While Tom Swift is trying to collect his senses and to remember,
in their sequence, the events which led up to his queer predicament,
may I take just a moment of your time, if you are a new reader, to tell
you who Tom was?
The first book of this series, “Tom Swift and His Motor Cycle,”
introduces you to the young inventor. His father, Barton Swift, was a
widower, living in the old homestead at Shopton on Lake Carlopa.
The Swift home was on the outskirts of the town and in a building not
far from the house Barton Swift began work on a series of inventions
which were destined to make him and his son famous. Tom’s mother
was dead, but Mrs. Baggert, the housekeeper, looked well after the
material welfare of Tom and his father.
In due time Tom began to follow in his father’s footsteps, working
at small inventions until, when a sturdy youth, he became possessed
of a motorcycle. He bought the machine of an eccentric individual
named Wakefield Damon, who lived in the neighboring town of
Waterfield. Mr. Damon set out to learn to ride his new machine.
“But bless my porous plaster!” the queer man would exclaim in
telling the story, “I never thought the contraption was going to climb
trees!”
Which it did, or tried to, because Mr. Damon did not know how to
manage it. The result was that the rider was injured and the
motorcycle badly smashed and Tom, near whose home the accident
occurred, became the owner of the machine.
How he repaired it, added some improvements, and what he did
with the machine are fully set forth in the book. It was the beginning
of a long friendship with Mr. Damon, and also the real start of Tom’s
inventive career.
Those of you who have followed him in his successes, from his
motor boat to “Tom Swift’s Chest of Secrets,”—the volume
immediately preceding this one—need not be told of Tom’s activities.
He had made some wonderful pieces of apparatus and had had
some startling adventures. In some of these his father and Mr.
Damon had shared. So, also, had Ned Newton, Tom’s closest friend
and now the treasurer of the Swift Construction Company.
Mary Nestor, of whom Ned had spoken, was a beautiful girl
whom Tom hoped to marry some day, and Ned Newton was
interested in a similar manner in Mary’s friend, Helen Morton.
As Tom sat there in the darkness, trying to puzzle out where he
was and how he had gotten there, his thought flashed to Mary.
“I wonder what she’ll think?” he mused. “I’d better get to a
telephone and explain. Let’s see. I was coming back from town and I
saw some fellow sneaking along behind the bushes. I met Ned. I
went down a flight of stairs in a hole—though how they could be
there and I not know it, is more than I can fathom. Then they doped
me. But who did it and why, I don’t know. I’ll soon find out, though.
Wonder how long I’ve been here? Feels like a week, I’m so stiff. But
I’m not hurt, thank goodness!”
Tom stretched out his arms in the darkness. They responded to
the action of his muscles. But when he tried to get up and walk—
well, he simply could not!
“Chained fast!” cried Tom, aloud. His hands had sought his left
ankle when he found that something held him fast there, and his
fingers had come in contact with a chain.
For a moment he felt a sinking sensation. To be chained fast in
the dark, at the bottom of some cave or dungeon, located he knew
not where, was enough to take the heart out of any one. But not for
long did Tom Swift give way to despair.
He gave a vigorous tug to the chain about his ankle. After all, it
might only be lying across it or loosely twisted. But it needed only
one effort on his part to loosen the links to let him know that he was
bound fast. Whoever had put the chain on his ankle had done so
with serious intentions of holding the young inventor captive.
“Well, this is worse and more of it!” he mused grimly. “What does
it all mean? It can’t be a plot to kidnap me. No one knew I was
coming across the lots, for I didn’t know it myself until the last
minute. And seeing that man sneaking along, discovering the secret
stairs—it was all a series of accidents. Though it’s likely to prove a
serious accident for me if I can’t get loose.”
Tom was nothing if not practical, and first he felt about with his
hands to determine the exact nature of what it was that held him fast.
He discovered, by the sense of touch, that something in the nature of
a handcuff was snapped about his ankle. To this cuff, or leg-iron,
was attached a chain. By following this, link by link, Tom found that
the chain was made fast to a ring of iron which, in turn, was sunk into
the stone side wall of the cave or tunnel in which he now found
himself.
How far he was removed from the bottom of the flight of secret
steps where he had been made unconscious, he did not know, any
more than he knew where he was.
Having discovered what it was that held him fast and the nature
of the chain and its fastenings, Tom, who had risen to his feet, stood
silent a moment, listening. It was very black and very still in the cave,
if such it was, and from the earthy, damp smell he concluded that he
must be underground, or at least in some vault or cellar.
By test Tom found that he could move about five feet, such being
the length of the chain. The leg-iron had been snapped or riveted
about his ankle outside of his trousers. It was not tight enough to
cause any pain, but it was snug enough to be impossible of removal.
“They’ve got me as tight as an animal in a trap!” grimly exclaimed
the youth, when, by a series of tugs, he ascertained how securely
the end of the chain was fast in the rocky wall. “Just like a trap, or a
prisoner in an old-time dungeon!” bitterly reflected the young man.
“All it needs to make a moving picture film is some beautiful maiden
to come to my rescue with a file——”
Tom’s spoken words (for he was talking aloud to himself) came to
a sudden end as he clapped a hand to the pocket of his coat.
“I’ve got ’em!” he fairly shouted, and he drew out a small paper
parcel in which were two keen files. They were part of the purchases
made just before stumbling on the mysterious man and finding the
steps in the queer opening.
“Files—the hardest and best made!” he told himself. “They’ll cut
through anything but a diamond. Luck’s with me, after all. They didn’t
know I had these! Oh, boy!”
Everything seemed changed now! Though he was held fast,
though he was in some secret dungeon, hope sang a song of joy in
his heart.
For a moment Tom debated with himself as to the best end of the
chain at which to begin filing. It would be more comfortable with that
leg-iron off his ankle, but by feeling it in the darkness he could tell
that it was broad and thick. It would take some time for even the
keen, hard file to cut through it.
“I’ll file through one of the links close to the leg-iron,” decided
Tom. “That won’t leave much to carry around, and it won’t take long
to cut through a link—that is, unless they’re made of case-hardened
steel.”
But the chain was of the ordinary sort, made of soft iron, and it
did not take the young inventor long, practiced as he was in the use
of tools, to file apart one of the links. True it was not easy in the
darkness, and, more than once, the file slipped and cut Tom’s hands
or fingers, for he changed from left to right and back to left in using
the file, having taught himself to be ambidextrous in many
operations.
At last he could feel that the link was nearly severed and then,
inserting the small ends of the two files in it, he pried them apart.
This leverage broke the thin remaining bit of iron and Tom was free.
That is, he was free to move about as he pleased, but he was still
within the dark cave, and where it was he could not imagine.
“I’ve got to feel my way about,” he told himself. “It’s as dark as
the inside of a pocket.”
So dark was it that Tom had to tread cautiously and with
outstretched hands lest he bump into some obstruction. Whether he
was moving toward the steps down which he had come or in the
opposite direction, Tom had no means of knowing. His sense of
touch alone guided him.
He could feel that he was walking along a tunnel, but the size of it
he could only guess at. Then, suddenly, on making an elbow turn, he
saw, glimmering in the distance, a faint light. It was the light of day,
Tom knew, and by that he realized that he had been held captive all
night.
“That makes it bad,” he mused. “Dad will have done a lot of
worrying about me, I’m afraid. But I guess I’ll soon be out of here.”
Then, to his ears, came the murmur of voices—voices strange to
him. So faint was the light in the distance that it was of no service to
him where he stood waiting in the darkness; waiting for he knew not
what.
The voices increased in loudness, showing that the speakers
were approaching. Then he heard footsteps echoing strangely in the
hollow tunnel.
“If there’s going to be a fight I’d better get ready for it,” Tom told
himself fiercely. He stooped and began feeling about on the ground
for a loose rock or a club. But he could find nothing. Then like a flash
it came to him.
“One of the files! They’re pretty sharp on the handle end. As good
as a knife! I’ll use it like a knife if I have to,” he mused desperately.
He drew one of the files from his pocket, grasped it firmly, and
waited in the darkness for what was to happen next.
CHAPTER III
MASKED MEN

After the treatment that had been accorded him, Tom Swift rather
welcomed than otherwise a chance to come to grips with the men
who were responsible for his position. Usually even-tempered and
generous, just now he felt eager for vengeance and he would not
have cared much if two men had attacked him at once.
Strangely enough he did not feel weak or ill now. He had,
somewhat, when he first regained his senses after having been
overpowered by some drug. But his brain had cleared and he kept
himself in such good physical trim all the while that even a night of
unconsciousness had not sapped his strength.
The light in the distance did not increase any, from which Tom
gathered that it was full daylight with the sun well above the horizon,
and after that first murmur of voices and the sound of footsteps these
sounds did not come any nearer. Nor did Tom catch a glimpse of any
figures between himself and that little circle of light.
Then from some point outside the cave or tunnel he heard voices
calling. They were louder than the first, and there seemed to be
some dispute or disturbance.
The voices rose to a high pitch and then died away. Silence
followed, and then came the sound of retreating footsteps.
“They’re going away!” exulted Tom. “Now I’ve got a chance to
walk toward that daylight and see where I am. Maybe I’d better wait
a few minutes, though. They may come back.”
He waited what he thought was several minutes and then,
hearing no other sounds of voices or footsteps, began a cautious
approach toward that gleam of light. What a blessed thing light was,
after all that black and clinging darkness!
In silence Tom crept on, advancing one foot after the other
cautiously, and keeping one hand extended to give warning of his
approach toward any obstruction while in his other hand he held the
file like a dagger, ready to use.
But there was no occasion for this. A little later he found himself
standing in a circle of daylight illumination that filtered down an
inclined shaft which led out of a tunnel, such as Tom could now
ascertain he was in. A natural tunnel it appeared to be, with rocks
jutting out here and there in the earthen sides. Roughly the tunnel
was in the form of a half circle, the floor being flat and the roof
arched. The inclined entrance led upward in a gentle slope.
“Well, now to see what’s up there!” said Tom to himself, taking a
long breath and holding his weapon ready. He tensed his muscles
and steeled his nerves for what he felt might be a desperate
struggle. Yet he did not shrink back.
As he advanced cautiously, step by step, up the incline that led to
daylight and the outer world, he felt at first a sense of disappointment
when he saw no one with whom he might come to grips. He had
been treated so meanly that it would have been a source of
satisfaction to have had it out in a rough-and-tumble fight with those
responsible.
But, to his surprise, Tom pushed his way out through a tangle of
underbrush and bushes which grew about this end of the tunnel and
found none to dispute him. This surprise was added to when he
looked about him and found out where he was.
“On Barn Door Island!” exclaimed Tom. “Of all places! Barn Door
Island! But how did I get here? It’s miles away from where I went
down those steps near our plant. Of all places! Barn Door Island!”
This was a small island in Lake Carlopa which had been named
Barn Door because, some time or other, one of the early settlers
happened to remark that it was no larger than the door of a barn.
The island was at the end of the lake farthest removed from Shopton
and the Swift plant.
“I never knew there was an entrance to a tunnel here!” said Tom,
as he looked about him. “But then I’ve never explored here very
much.”
Nor had any of the other lads of Shopton. Barn Door Island was a
barren place—merely a collection of scrubby trees and tangled
bushes and great boulders set down at the swampy end of Lake
Carlopa. It was not a good fishing location and too dreary for picnic
parties, so Barn Door was seldom visited.
“But if I had an idea there was a tunnel entrance here—the
beginning of a passage that led under the lake and under the land

You might also like