Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
54 views

Functional Python Programming: Use a functional approach to write succinct, expressive, and efficient Python code, 3rd Edition Lott - Quickly download the ebook to explore the full content

The document promotes an extensive collection of ebooks available for download at textbookfull.com, including titles on Python programming and functional programming. It highlights specific books such as 'Functional Python Programming' and 'Learn Python Programming', providing links for instant access. Additionally, it emphasizes the versatility of Python and the benefits of functional programming techniques.

Uploaded by

raymieyavish
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
54 views

Functional Python Programming: Use a functional approach to write succinct, expressive, and efficient Python code, 3rd Edition Lott - Quickly download the ebook to explore the full content

The document promotes an extensive collection of ebooks available for download at textbookfull.com, including titles on Python programming and functional programming. It highlights specific books such as 'Functional Python Programming' and 'Learn Python Programming', providing links for instant access. Additionally, it emphasizes the versatility of Python and the benefits of functional programming techniques.

Uploaded by

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

Explore the full ebook collection and download it now at 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/

OR CLICK HERE

DOWLOAD EBOOK

Browse and Get More Ebook Downloads Instantly at https://textbookfull.com


Click here to visit textbookfull.com and download textbook now
Your digital treasures (PDF, ePub, MOBI) await
Download instantly and pick your perfect format...

Read anywhere, anytime, on any device!

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-loucas/

textbookfull.com

Learn Python Programming A beginner s guide to learning


the fundamentals of Python language to write efficient
high quality code Romano
https://textbookfull.com/product/learn-python-programming-a-beginner-
s-guide-to-learning-the-fundamentals-of-python-language-to-write-
efficient-high-quality-code-romano/
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/
textbookfull.com

Functional Programming in C#: How to write better C# code


1st Edition Enrico Buonanno

https://textbookfull.com/product/functional-programming-in-c-how-to-
write-better-c-code-1st-edition-enrico-buonanno/

textbookfull.com
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

A Functional Approach to Java: Augmenting Object-Oriented


Java Code with Functional Principles 1st Edition Ben
Weidig
https://textbookfull.com/product/a-functional-approach-to-java-
augmenting-object-oriented-java-code-with-functional-principles-1st-
edition-ben-weidig/
textbookfull.com

Python Projects for Beginners: A Ten-Week Bootcamp


Approach to Python Programming Milliken

https://textbookfull.com/product/python-projects-for-beginners-a-ten-
week-bootcamp-approach-to-python-programming-milliken/

textbookfull.com

Teach Your Kids to Code A Parent Friendly Guide to Python


Programming 1st Edition Bryson Payne

https://textbookfull.com/product/teach-your-kids-to-code-a-parent-
friendly-guide-to-python-programming-1st-edition-bryson-payne/

textbookfull.com

Effective Python 90 Specific Ways to Write Better Python


2nd Edition Brett Slatkin

https://textbookfull.com/product/effective-python-90-specific-ways-to-
write-better-python-2nd-edition-brett-slatkin/

textbookfull.com
Functional Python
Programming
Third Edition

Use a functional approach to write succinct,


expressive, and efficient Python code

Steven F. Lott

BIRMINGHAM—MUMBAI
“Python” and the Python logo are trademarks of the Python Software Foundation.
Functional Python Programming
Third Edition
Copyright © 2022 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.

Senior Publishing Product Manager: Denim Pinto


Acquisition Editor – Peer Reviews: Gaurav Gavas
Project Editor: Parvathy Nair
Development Editor: Lucy Wan
Copy Editor: Safis Editing
Technical Editor: Karan Sonawane
Indexer: Hemangini Bari
Proofreader: Safis Editing
Presentation Designer: Sandip Tadge

First published: January 2015


Second edition: April 2018
Third edition: December 2022

Production reference: 1221222


Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80323-257-7
www.packt.com
Foreword

Python is an incredibly versatile language that offers a lot of perks for just about every
group. For the object-oriented programming fans, it has classes and inheritance. When
we talk about functional programming, it has functions as a first-class type, higher-order
functions such as map and reduce, and a handy syntax for comprehensions and generators.
Perhaps best of all, it doesn’t force any of those on the user – it’s still totally OK to write a
script in Python without a single class or function and not feel guilty about it.

Thinking in terms of functional programming, having in mind the goals of minimizing state
and side effects, writing pure functions, reducing intermediary data, and what depends on
what else will also allow you to see your code under a new light. It’ll also allow you to
write more compact, performant, testable, and maintainable code, where instead of writing
a program to solve your problem, you “write the language up”, adding new functions to
it until expressing the solution you designed is simple and straightforward. This is an
extremely powerful mind shift – and an exercise worth doing. It’s a bit like learning a
new language, such as Lisp or Forth (or German, or Irish), but without having to leave the
comfort of your Python environment.

Not being a pure functional language has its costs, however. Python lacks many features
functional languages can use to provide better memory efficiency and speed. Python’s
strongest point remains its accessibility – you can fire up your Python interpreter and
start playing with the examples in this book right away. This interactive approach allows
exploratory programming, where you test ideas easily, and only later need to incorporate
them into a more complex program (or not – like I said, it’s totally OK to write a simple
script).

This book is intended for people already familiar with Python. You don’t need to know
much about functional programming – the book will guide you through many common
approaches, techniques, and patterns used in functional programming and how they can
be best expressed in Python. Think of this book as an introduction – it’ll give you the basic
tools to see, think, and express your ideas in functional terms using Python.

Ricardo Bánffy

Software Engineer, Architect, Evangelist, and Passionate Pythonista


Contributors

About the author


Steven F. Lott has been programming since computers were large, expensive, and rare.
Working for decades in high tech has given him exposure to a lot of ideas and techniques;
some are bad, but most are useful and helpful to others.

Steven has been working with Python since the ‘90s, building a variety of tools and
applications. He’s written a number of titles for Packt Publishing, include Mastering
Object-Oriented Python, Modern Python Cookbook, and Functional Python Programming.

He’s a technomad, and lives on a boat that’s usually located on the east coast of the US. He
tries to live by the words, “Don’t come home until you have a story.”
About the reviewers
Alex Martelli is a Fellow of the Python Software Foundation, a winner of the Frank
Willison Memorial Award for contributions to the Python community, and a top-page
reputation hog on Stack Overflow. He spent 8 years with IBM Research, then 13 years
at Think3 Inc., followed by 4 years as a consultant, and lately 17 years at Google. He
has taught programming languages, development methods, and numerical computing at
Ferrara University and other venues.

Books he has authored or co-authored include two editions of Python Cookbook, four
editions of Python in a Nutshell, and a chapter in Beautiful Teams. Dozens of his interviews
and tech talks at conferences are available on YouTube. Alex’s proudest achievement are
the articles that appeared in Bridge World (January and February 2000), which were hailed
as giant steps towards solving issues that had haunted contract bridge theoreticians for
decades, and still get quoted in current bridge-theoretical literature.

Tiago Antao has a BEng in Informatics and a PhD in Life Sciences. He works in the
Big Data space, analyzing very large datasets and implementing complex data processing
algorithms. He leverages Python with all its libraries to carry out scientific computing and
data engineering tasks. He also uses low-level programming languages like C, C++, and
Rust to optimize critical parts of algorithms. Tiago develops on an infrastructure based on
AWS, but has used on-premises computing and scientific clusters for most of his career.

While he currently works in industry, he also has exposure to the academic side of scientific
computing, with two data analysis postdocs at the universities of Cambridge and Oxford,
and a research scientist position at the University of Montana, where he set up, from
scratch, the scientific computing infrastructure for the analysis of biological data.

He is one of the co-authors of Biopython, a major bioinformatics package written in Python.


He wrote Bioinformatics with Python Cookbook, which is on its third edition. He has also
authored and co-authored many high-impact scientific articles in the field of bioinformatics.
Join our community Discord space
Join our Python Discord workspace to discuss and know more about the book:
https://packt.link/dHrHU
Table of Contents

Preface xxi

Chapter 1: Understanding Functional Programming 1

The functional style of programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Comparing and contrasting procedural and functional styles . . . . . . . . . . . . . . . . . . . . . 4
Using the functional paradigm • 5
Using a functional hybrid • 8
The stack of turtles • 9
A classic example of functional programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Exploratory data analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Convert an imperative algorithm to functional code • 18
Convert step-wise computation to functional code • 18
Revise the sqrt() function • 20
Data cleansing steps • 20
(Advanced) Optimize this functional code • 23

Chapter 2: Introducing Essential Functional Concepts 25

Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


Pure functions • 27
Higher-order functions • 29
Immutable data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Strict and non-strict evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Lazy and eager evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Recursion instead of an explicit loop state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Functional type systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Familiar territory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Learning some advanced concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Apply map() to a sequence of values • 44
Function vs. lambda design question • 45
Optimize a recursion • 45

Chapter 3: Functions, Iterators, and Generators 47

Writing pure functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


Functions as first-class objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Using strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using tuples and named tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Using generator expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Exploring the limitations of generators • 63
Combining generator expressions • 65
Cleaning raw data with generator functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Applying generators to built-in collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Generators for lists, dicts, and sets • 69
Using stateful mappings • 73
Using the bisect module to create a mapping • 76
Using stateful sets • 78
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Rewrite the some_function() function • 79
Alternative Mersenne class definition • 80
Alternative algorithm implementations • 81
Map and filter • 82
Dictionary comprehension • 82
Raw data cleanup • 82

Chapter 4: Working with Collections 85

An overview of function varieties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86


Working with iterables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Parsing an XML file • 89
Parsing a file at a higher level • 92
Pairing up items from a sequence • 95
Using the iter() function explicitly • 98
Extending an iteration • 100
Applying generator expressions to scalar functions • 104
Using any() and all() as reductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Using len() and sum() on collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Using sums and counts for statistics • 111
Using zip() to structure and flatten sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Unzipping a zipped sequence • 117
Flattening sequences • 118
Structuring flat sequences • 120
Structuring flat sequences – an alternative approach • 124
Using sorted() and reversed() to change the order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Using enumerate() to include a sequence number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Palindromic numbers • 129
Hands of cards • 130
Replace legs() with pairwise() • 131
Expand legs() to include processing • 132

Chapter 5: Higher-Order Functions 133

Using max() and min() to find extrema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134


Using Python lambda forms • 138
Lambdas and the lambda calculus • 140
Using the map() function to apply a function to a collection . . . . . . . . . . . . . . . . . . . . . . 141
Working with lambda forms and map() • 143
Using map() with multiple sequences • 144
Using the filter() function to pass or reject data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Using filter() to identify outliers • 149
The iter() function with a sentinel value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Using sorted() to put data in order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Overview of writing higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Writing higher-order mappings and filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Unwrapping data while mapping • 156
Wrapping additional data while mapping • 159
Flattening data while mapping • 161
Structuring data while filtering • 164
Building higher-order functions with callables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
Assuring good functional design • 168
Review of some design patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Classification of state • 173
Classification of state, Part II • 174
Optimizing a file parser • 175
Chapter 6: Recursions and Reductions 177

Simple numerical recursions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178


Implementing manual tail-call optimization • 180
Leaving recursion in place • 181
Handling difficult tail-call optimization • 182
Processing collections through recursion • 184
Tail-call optimization for collections • 185
Using the assignment (sometimes called the “walrus”) operator in recursions • 187
Reductions and folding a collection from many items to one . . . . . . . . . . . . . . . . . . . . . . 188
Tail-call optimization using deques • 190
Group-by reduction from many items to fewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Building a mapping with Counter • 195
Building a mapping by sorting • 196
Grouping or partitioning data by key values • 198
Writing more general group-by reductions • 203
Writing higher-order reductions • 205
Writing file parsers • 207
Parsing CSV files • 211
Parsing plain text files with headers • 214
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Multiple recursion and caching • 219
Refactor the all_print() function • 219
Parsing CSV files • 219
Classification of state, Part III • 220
Diesel engine data • 220

Chapter 7: Complex Stateless Objects 223

Using tuples to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224


Using NamedTuple to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
Using frozen dataclasses to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Complicated object initialization and property computations . . . . . . . . . . . . . . . . . . . . . 237
Using pyrsistent to collect data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Avoiding stateful classes by using families of tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
Computing Spearman’s rank-order correlation • 252
Polymorphism and type pattern matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Frozen dictionaries • 263
Dictionary-like sequences • 264
Revise the rank_xy() function to use native types • 265
Revise the rank_corr() function • 265
Revise the legs() function to use pyrsistent • 265

Chapter 8: The Itertools Module 267

Working with the infinite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269


Counting with count() • 269
Counting with float arguments • 271
Re-iterating a cycle with cycle() • 275
Using cycle() for data sampling • 276
Repeating a single value with repeat() • 278
Using the finite iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Assigning numbers with enumerate() • 281
Running totals with accumulate() • 284
Combining iterators with chain() • 286
Partitioning an iterator with groupby() • 287
Merging iterables with zip_longest() and zip() • 290
Creating pairs with pairwise()) • 290
Filtering with compress() • 291
Picking subsets with islice() • 293
Stateful filtering with dropwhile() and takewhile() • 295
Two approaches to filtering with filterfalse() and filter() • 297
Applying a function to data via starmap() and map() • 298
Cloning iterators with tee() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
The itertools recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Optimize the find_first() function • 306
Compare Chapter 4 with the itertools.pairwise() recipe • 306
Compare Chapter 4 with itertools.tee() recipe • 307
Splitting a dataset for training and testing purposes • 307
Rank ordering • 307

Chapter 9: Itertools for Combinatorics – Permutations and Combina-


tions 309

Enumerating the Cartesian product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310


Reducing a product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
Computing distances • 314
Getting all pixels and all colors • 318
Performance improvements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
Rearranging the problem • 323
Combining two transformations • 324
Permuting a collection of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
Generating all combinations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
Combinations with replacement • 333
Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Alternative distance computations • 336
Actual domain of pixel color values • 338
Cribbage hand scoring • 339

Chapter 10: The Functools Module 343

Function tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344


Memoizing previous results with cache . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Defining classes with total ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Applying partial arguments with partial() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Reducing sets of data with the reduce() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Combining map() and reduce() • 356
Using the reduce() and partial() functions • 358
Using the map() and reduce() functions to sanitize raw data • 360
Using the groupby() and reduce() functions • 362
Avoiding problems with reduce() • 366
Handling multiple types with singledispatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Compare string.join() and reduce() • 370
Extend the comma_fix() function • 370
Revise the clean_sum() function • 371

Chapter 11: The Toolz Package 373

The itertools star map function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374


Reducing with operator module functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Using the toolz package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Some itertoolz functions • 379
Some dicttoolz functions • 385
Some functoolz functions • 386
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
Replace true division with a fraction • 391
Color file parsing • 391
Anscombe’s quartet parsing • 392
Waypoint computations • 393
Waypoint geofence • 393
Callable object for the row_counter() function • 394

Chapter 12: Decorator Design Techniques 397

Decorators as higher-order functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398


Using the functools update_wrapper() function • 403
Cross-cutting concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Composite design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Preprocessing bad data • 407
Adding a parameter to a decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Implementing more complex decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Complicated design considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Datetime conversions • 421
Optimize a decorator • 423
None-tolerant functions • 423
Logging • 424
Dry-run check • 425

Chapter 13: The PyMonad Library 427

Downloading and installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428


Functional composition and currying . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Using curried higher-order functions • 431
Functional composition with PyMonad • 432
Functors – making everything a function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
Using the lazy ListMonad() monad • 436
Monad bind() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
Implementing simulation with monads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Additional PyMonad features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Revise the arctangent series • 449
Statistical computations • 450
Data validation • 450
Multiple models • 451

Chapter 14: The Multiprocessing, Threading, and Concurrent.Futures


Modules 453

Functional programming and concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454


What concurrency really means . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
The boundary conditions • 455
Sharing resources with process or threads • 456
Where benefits will accrue • 457
Using multiprocessing pools and tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Processing many large files • 460
Parsing log files – gathering the rows • 462
Parsing log lines into named tuples • 463
Parsing additional fields of an Access object • 467
Filtering the access details • 471
Analyzing the access details • 472
The complete analysis process • 473
Using a multiprocessing pool for concurrent processing . . . . . . . . . . . . . . . . . . . . . . . . . . 474
Using apply() to make a single request • 478
More complex multiprocessing architectures • 479
Using the concurrent.futures module • 479
Using concurrent.futures thread pools • 480
Using the threading and queue modules • 481
Using async functions • 482
Designing concurrent processing • 483
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Lazy parsing • 487
Filter access path details • 488
Add @cache decorators • 489
Create sample data • 489
Change the pipeline structure • 490

Chapter 15: A Functional Approach to Web Services 491

The HTTP request-response model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492


Injecting state through cookies • 495
Considering a server with a functional design • 496
Looking more deeply into the functional view • 497
Nesting the services • 498
The WSGI standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
Raising exceptions during WSGI processing • 503
Pragmatic web applications • 505
Defining web services as functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
Flask application processing • 508
The data access tier • 513
Applying a filter • 515
Serializing the results • 516
Serializing data with JSON or CSV formats • 518
Serializing data with XML and HTML • 519
Tracking usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
WSGI application: welcome • 524
WSGI application: demo • 524
Serializing data with XML • 525
Serializing data with HTML • 525

Other Books You Might Enjoy 52

Index 53
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 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 can’t easily create purely functional programs in Python. Python lacks a number of
features that would be required for this. We don’t have unlimited recursion, for example,
we don’t have lazy evaluation of all expressions, and we don’t 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 ob-
jects. Python also offers a number of higher-order functions. The built-in map(), filter(),
and functools.reduce() functions are widely used in this role, and less obvious are
functions such as sorted(), min(), and max().

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 de-
sign 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.
xxii Preface

We’ll 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 more experienced programmers who want to create succinct, expressive
Python programs by borrowing techniques and design patterns from functional program-
ming languages. Some algorithms can be expressed elegantly in a functional style; we
can—and should—adapt this to make Python programs more readable and maintainable.

This is not intended as a tutorial on Python. This book assumes some familiarity with the
language and the standard library. For a foundational introduction to Python, consider
Learn Python Programming, Third Edition: https://www.packtpub.com/product/learn-p
ython-programming-third-edition/9781801815093.

While we cover the foundations of functional programming, this is not a complete review of
the various kinds of functional programming techniques. Having an exposure to functional
programming in another language can be helpful.

What this book covers


We can decompose this book into two general kinds of topics:

• Essentials of functional programming in Python. This is the content of Chapters 1


through 7.

• Library modules to help create functional programs. This is the subject of the
remaining chapters of the book. Chapter 12 includes both fundamental language and
library topics.

Chapter 1, Understanding Functional Programming, introduces some of the techniques that


characterize functional programming. We’ll identify some of the ways to map those features
to Python. We’ll also address some ways that the benefits of functional programming accrue
when we use these design patterns to build Python applications.
Preface xxiii

Chapter 2, Introducing Essential Functional Concepts, delves into central features of the
functional programming paradigm. We’ll look at each in some detail to see how they’re
implemented in Python. We’ll also point out some features of functional languages that
don’t apply well to Python. In particular, many functional languages have complex type-
matching rules required to support compiling and optimizing.

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

Chapter 4, 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 any() and all(), which reduce a collection of values to a single
result.

Chapter 5, Higher-Order Functions, examines the commonly used higher-order functions


such as map() and filter(). It also shows a number of other higher-order functions as
well as how we can create our own functions that work with functions or return functions.

Chapter 6, Recursions and Reductions, teaches how to design an algorithm using recursion
and then optimize it into a high-performance for statement. We’ll also look at some other
reductions that are widely used, including collections.Counter().

Chapter 7, Complex Stateless Objects, showcases a number of ways that we can use immutable
tuples, typing.NamedTuple, and the frozen @dataclass instead of stateful objects. We’ll
also look at the pyrsistent module as a way to create immutable objects. Immutable
objects have a simpler interface than stateful objects: we never have to worry about
abusing an attribute and setting an object into some inconsistent or invalid state.

Chapter 8, The Itertools Module, examines a number of functions in the itertools standard
library module. This collection of functions simplifies writing programs that deal with
collections or generator functions.
xxiv Preface

Chapter 9, Itertools for Combinatorics – Permutations and Combinations, covers the combina-
toric functions in the itertools module. These functions are more specialized than those
in the previous chapter. This chapter includes some examples that illustrate ill-considered
use of these functions and the consequences of combinatoric explosion.

Chapter 10, The Functools Module, focuses on how to use some of the functions in the
functools module for functional programming. A few functions in this module are more
appropriate for building decorators, and they are left for Chapter 12, Decorator Design
Techniques.

Chapter 11, The Toolz Package, covers the toolz package, a number of closely related
modules that help us write functional programs in Python. The toolz modules parallel
the built-in itertools and functools modules, providing alternatives that are often more
sophisticated and make better use of curried functions.

Chapter 12, Decorator Design Techniques, covers how we 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: we’ll look at ways that overly complex decorators can become
confusing rather than helpful.

Chapter 13, 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 expressions and statements, the monad feature
is more instructive than practical.

Chapter 14, The Multiprocessing, Threading, and Concurrent.Futures Modules, points out
an important consequence of good functional design: we can distribute the processing
workload. Using immutable objects means that we can’t corrupt an object because of poorly
synchronized write operations.

Chapter 15, 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. We’ll see ways to
Preface xxv

leverage functional programming concepts for building responsive, dynamic web content.

Chapter 16, A Chi-Squared Case Study, is a bonus, online-only case study applying a number
of functional programming techniques to a specific exploratory data analysis problem. We
will apply a 𝜒 2 statistical test to some complex data to see if the results show ordinary
variability, or if they are an indication of something that requires deeper analysis. You can
find the case study here: https://github.com/PacktPublishing/Functional-Python-P
rogramming-3rd-Edition/blob/main/Bonus_Content/Chapter_16.pdf.

To get the most out of this book


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

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.

Python 3.10 is required. The examples have also been tested with Python 3.11, and work
correctly. For data science purposes, it’s often helpful to start with the conda tool to create
and manage virtual environments. It’s not required, however, and readers should be able
to use any available Python.

Additional packages are generally installed with pip. The command looks like this:

% python -m pip install toolz pymonad pyrsistent beautifulsoup4

Complete the exercises


Each chapter includes a number of exercises that help the reader apply the concepts in the
chapter to real code. Most of the exercises are based on code available from the book’s
repository on GitHub: https://github.com/PacktPublishing/Functional-Python-Pro
gramming-3rd-Edition.
xxvi Preface

In some cases, the reader will notice that the code provided on GitHub includes partial
solutions to some of the exercises. These serve as hints, allowing the reader to explore
alternative solutions.

In many cases, exercises will need unit test cases to confirm they actually solve the problem.
These are often identical to the unit test cases already provided in the GitHub repository.
The reader should replace the book’s example function name with their own solution to
confirm that it works.

In some cases, the exercises suggest writing a response document to compare and contrast
multiple solutions. It helps to find a mentor or expert who can help the reader by reviewing
these small documents for clarity and completeness. A good comparison between design
approaches will include performance measurements using the timeit module to show the
performance advantages of one design over another.

Download the example code files


The code bundle for the book is hosted on GitHub at https://github.com/PacktPublis
hing/Functional-Python-Programming-3rd-Edition. We also have other code bundles
from our rich catalog of books and videos available at https://github.com/PacktPublis
hing/. Check them out!

Download the color images


We also provide a PDF file that has color images of the screenshots/diagrams used in this
book. You can download it here: https://packt.link/OV1CB.

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

CodeInText: Indicates code words in the text, database table names, folder names, filenames,
file extensions, pathnames, dummy URLs, user input, and Twitter handles. For example:
“Python has other statements, such as global or nonlocal, which modify the rules for
variables in a particular namespace.”
Preface xxvii

Bold: Indicates a new term, an important word, or words you see on the screen, such as in
menus or dialog boxes. For example: “The base case states that the sum of a zero-length
sequence is 0. The recursive case states that the sum of a sequence is the first value plus
the sum of the rest of the sequence.”

A block of code is set as follows:

print("Hello, World!")

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

% conda create -n functional3 python=3.10

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 feedback@packtpub.com, and mention the book’s title in the
subject of your message. If you have questions about any aspect of this book, please email
us at questions@packtpub.com.

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 https://subscription.packtpub.com/help, click on the
Submit Errata button, search for your book, and enter the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet,
xxviii Preface

we would be grateful if you would provide us with the location address or website name.
Please contact us at copyright@packtpub.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have ex-
pertise in and you are interested in either writing or contributing to a book, please visit
http://authors.packtpub.com.

Share your thoughts


Once you’ve read Functional Python Programming, Third Edition, we’d love to hear your
thoughts! Scan the QR code below to go straight to the Amazon review page for this book
and share your feedback.

https://packt.link/r/1803232579

Your review is important to us and the tech community and will help us make sure we’re
delivering excellent quality content.
Random documents with unrelated
content Scribd suggests to you:
store of gratitude. In fact he had never even considered that he had
really rescued the child; he had simply carried her home.
He certainly felt grateful to Mrs. Dawson. It was not half as hard
to wait for trouble when he knew definitely that it was coming as it
was to sit around and wonder about it. He could act now. At first he
thought that he would go at once to Baxter’s, but he could not resist
the temptation to stay and try to find out who the men were who
were after him. He went quietly down to the corral, put the saddle
and bridle on Jed, and led him out a quarter of a mile in the
direction of Baxter’s quarters. He left the horse there in a well-
marked spot and stole cautiously back to his station near the cabin.
It was too dark to see his watch, but Scott judged that it must be
pretty close to midnight. Once more he settled down to wait and
listen but he knew what to expect now and was entirely free from
the creepy feeling of uncertainty which had so worked on his nerves
earlier in the night. After about an hour’s vigil he thought he heard a
faint sound far down the trail. He waited patiently but it was not
repeated. That, however, was not significant for they would probably
leave their horses at a safe distance and come the rest of the way
more quietly on foot. He continued to listen intently.
In about half an hour his patience was rewarded. A twig snapped
in the direction of the corral and a dark shadow crawled slowly
toward the cabin. Scott sat as still as the tree against which he
leaned. It made him shudder to think that he might have been in
that cabin with that crawling shadow sneaking up on him. The man
moved very cautiously and as silently as the death that he carried.
He avoided the glare of the light from the doorway and edged
around toward the side next to Scott. His progress was almost
imperceptible now but he finally reached the wall. He listened
intently for a moment and then raised himself cautiously to a level
with the window. For one second he stood in the glare of the
lamplight before he realized that there was no one within and then
he ducked quickly below the sill. He was quick to recognize the
disadvantage of being there in the light with a possible enemy in the
dark woods behind him.
Short as the time had been Scott had recognized Dugan and had
caught the gleam of light from something which glittered in his
hand. It was hard to realize that he had slept with that man for
three nights in that very cabin. He did not have long to think about it
for Dugan had made certain there was no one in the shack and was
retreating to the very patch of shade in which Scott was hiding. He
used the same stealthy caution with which he had approached the
cabin and seemed to Scott to be gliding toward him for all the world
like a snake. There was the same dull reflection every time he
advanced his right hand that Scott had noticed in the window. It
looked as though they were certain to meet if Dugan held to his
present course. Scott almost stopped breathing and braced himself
for the encounter. If only the man would come within reach. Scott
felt that he could handle Dugan if he could only get hold of him
before there was time to shoot.
Steadily the shadow advanced. Only eight feet separated him
from the man in the forest when he turned slowly toward the cabin
once more and settled down to watch. Scott could not have missed
him, as poor a shot as he was, but even now he was glad that he
was not armed. The idea of shooting a man in the back even when
that man was waiting to do the same thing to him was repulsive to
him.
Almost side by side the two men sat and watched in absolute
silence. Scott had been still for an hour before he came without
suffering the slightest inconvenience, now he suffered agonies. He
wanted to sneeze. He itched all over and had an almost
uncontrollable desire to scratch. His legs became cramped and he
felt that he would have to move them or scream. And still Dugan
waited patiently, toying silently with his revolver. Scott saw the
ridiculous side of the situation as well as the danger and grinned as
he planned what he would do when the day began to break.
Dugan seemed to realize that something was wrong. He rose
slowly and walked cautiously back to the window. He was bolder
now. His vigil had convinced him that there was no one around. He
made a careful survey of the inside of the cabin and then walked
boldly off in the direction of the corral.
Scott heaved a great sigh of relief, congratulated himself on his
foresight in getting Jed out of the way and sneaked cautiously out to
join him. Jed heard him coming and nickered loudly. Scott had no
doubt that Dugan heard it, but it was too late now to do him any
harm. He swung onto Jed’s back with a feeling of perfect safety and
cantered away to Baxter’s.
Baxter was standing in the door of his cabin waiting for him. “I
heard your horse a mile away,” he called in cheerful greeting. “Put
Jed in the corral and come tell me the story. I have been lying awake
all night just to hear it.”
CHAPTER XVI

AT THE RESERVOIR

Scott and Baxter lay awake far into the small hours of the
morning discussing the events of the past evening. Baxter had been
in the West long enough to have lost his aversion to a gun, if indeed
he had ever had any, and could not understand Scott’s scruples.
“If ever a man had need of gun,” he exclaimed, “you have now.
Here you are traipsing around the country with a bad man on your
trail and not so much as a cap pistol in your belt. Why, man, if you’d
had a gun there to-night you could have blown that skunk into
kingdom come and ended all this rumpus.”
“And thought about it all the rest of my life,” Scott replied.
Baxter looked at him hopelessly and gave it up. “Well, you ought
to be pretty safe up there at the dam if they don’t know you are
there. Ramsey is evidently looking out for you down there and I’ll
keep a weather eye on the pass here. Let’s go to sleep so that you
can get away from here in the morning before anybody sees you.”
The nerves of youth are easily settled and Scott was soon
sleeping as peacefully as though nothing had happened. At his first
snore Baxter raised up cautiously and crawled out of bed. He slipped
on his clothes and took his seat at the open doorway with his
revolver lying within easy reach. “Let that devil come snooping
around here,” he muttered, “and I’ll see how my scruples work on
him.”
At the first streak of day the faithful guardian arose and quietly
prepared breakfast. “Come out of it, Burton, and throw some of this
into you,” he called to Scott when all was ready.
“Why didn’t you call me earlier?” Scott complained.
“Because I had not been out dodging bullets all night and did not
need the sleep.”
“How about grub up there at the dam?” Scott asked. “I don’t
know anything about the place and never thought about provisions
last night.”
“Strange, not having anything else to think about,” Baxter
commented sarcastically. “Better take along a few things from here
to make sure, but the cabin up there is usually pretty well stocked, I
think. If you are ready we better be going; we are not so likely to
meet any one on the trail now.”
He threw such perishable provisions as he happened to have into
a bag and started for the corral. Scott saw him pick his revolver up
from the bench by the door and stick it into his holster.
It was just light enough to see when they started up the trail
which led over the pass. They were nearly to the place where they
were fighting the fire the day before when Baxter turned from the
trail into the heavier timber.
“What’s the big scare now,” Scott asked looking curiously around.
“May not be anything in it,” Baxter replied, “but old Benny up
there in the lookout tower has eyes like a hawk. If he sees anything
moving within fifty miles he hauls out those old field glasses and
identifies it. He might recognize you and spread the news all over
the country. He is all right and would not tell any one if he knew why
you were going, but he doesn’t know and has nothing to do but talk
gossip over the ’phone.”
So they stuck to the hillside in spite of the rough going and
managed to keep out of Benny’s sight.
“Now you are all right,” Baxter assured him. “This trail is not very
good but you can follow it easy enough and it will lead you straight
to the dam. There is not supposed to be any one up that way, but if
you should see any one duck.”
“I suppose there is a telephone up there?” Scott asked.
“Yes, and you better listen in on every call you hear, because
some of us may want to warn you, but don’t talk unless you are sure
who it is. They might try to locate you that way.”
“Well, so long,” Scott said, “I certainly appreciate what you have
done for me.”
“Haven’t had a chance yet,” Baxter replied cheerfully, “but I am
praying for the opportunity. Don’t you think you better take my gun?
I have another at the cabin.”
“No,” Scott laughed, “I might shoot myself. So long.”
Once more he was alone with his thoughts, taking to the hills like
a hunted animal and not knowing who might be on his trail or
where. At least he felt certain that no enemies were ahead of him
and he did not fear those who followed as long as he was in the
open. He was going into a new country and that always pleased him.
The thought of his dangers was soon wiped out by the wildness and
ruggedness of the mountains around him.
This trail was little more than a cow track and he lost sight of it
several times, but Jed followed it as easily as a hound no matter
how vague it seemed to Scott. If this was the only trail to the dam
he thought the supervisor had picked a very good hiding place for
him. Here and there the mountains receded enough to make a fairly
respectable valley, but for the most part they crowded in pretty close
and left little more than a narrow cañon. There were traces of a dry
stream bed in the bottom of it and Scott guessed that it was the
spillway for the dam in time of flood. He noticed that if there should
be much of a run-off there would be scant room for the trail.
After two hours of steady climbing Jed emerged into a small flat,
grassy and an ideal meadow. At the upper end of the flat was a
heavy mason work wall, twenty feet high in the middle and
stretching clear across from slope to slope. Back of it was a great
amphitheater surrounded by mountain peaks. It was a magnificent
picture and Scott sat for a few minutes drinking it in. The grandeur
of it awed him a little, but it had a wonderful, mysterious beauty that
fascinated him. He had often read of the eagle’s eyrie on the
mountain peaks and now he felt that he had found it. The prospect
of a week in that little cabin on the end of the dam would have been
an unadulterated joy to him if it had not been for the silent hunter
on the slopes below.
“Well, Jed, old boy, they were mighty considerate of you, anyway.
I don’t know what there is in that cabin but if it is half as well
stocked as this meadow I’ll be satisfied.”
He threw the saddle and bridle on the ground in one corner of the
meadow near the end of the dam and turned Jed loose to graze. A
tiny stream trickled through the dam, in one place, filling a little
basin in the sod of the meadow. Jed drank long and deep and
seemed perfectly contented with his surroundings. There was no
danger of his wandering off even if he had not been so faithfully
attached to Scott. No dog could have thought more of its master.
An examination of the cabin showed ample supplies to withstand
a long siege. The view back into the encircling mountains was
superb and down through the cut of the cañon was a vista of hill
and gorge that extended clear to the main valley miles away. There
was eighteen feet of crystal clear water in the reservoir which was
about twenty acres in extent. To a man from the lake-sprinkled
section of New England it was a welcome sight. It was the most
water he had seen in that semi-arid country.
The dam itself was a rather poorly constructed mason work affair
and its safety was a matter of anxiety every spring to the ranchers
who lived in the valley below. Since it had come into the hands of
the Service, a man had been stationed there whenever the melting
of the snows in the surrounding mountains threatened an overflow.
Scott could not imagine a more pleasant job under normal
conditions. He even felt that he could enjoy it now for he felt very
little fear of not being able to take care of himself in such a place.
He marked the height of the water so that he could note its
progress and went back into the cabin to fix it up for his occupancy.
It was a cozy little place but Scott had not been in there long when
he began to feel uneasy. The same old feeling of being trapped was
stealing over him once more. He kept going to the door to peer
down the cañon, and was constantly glancing at the window, half
expecting to see Dugan’s leering face and that glittering something
in his hand. He tried his best to forget it and busy himself with the
work in hand, but he could not do it. A few minutes in the open
restored his nerve perfectly, but it began slipping again as soon as
he returned to the cabin.
Scott hated to give in to these fears which he felt were almost
entirely unwarranted, but he was forced to recognize that it would
be out of the question for him to stay in the cabin. He would go
crazy in there. It was a new sensation for a man who had always
prided himself on not having any nerves, and just because it was
new it was harder to bear.
“It’s no use,” Scott admitted to himself after struggling for an hour
to stick it out. “I might as well own up to being a coward and act
accordingly.”
He went outside and looked for a good place to camp. There was
no tent in the outfit but he did not need one. It seldom rained and if
it should the cabin was there for shelter. He selected a little flat
bench on the side of the cañon, near the cabin and slightly above it.
It was backed by steep, overhanging rocks and could be approached
only from the direction of the cabin. He could overlook the trail up
the cañon but was protected from view by a thin screen of aspens.
He soon had a cozy little nest rigged up there and felt all his old
assurance returning. The house was the handicap; here in the open
he felt on an even footing with every man. The telephone was his
problem now. He was supposed to listen for messages from below
and yet he felt that he could not even listen intelligently cooped up
there in the cabin corner with that ’phone where he could not even
see out of the door or window.
A brilliant idea occurred to him. Why not move the ’phone up to
the camp? There were tools for repairing the telephone line in all the
cabins; he had everything that he needed. In an hour he had moved
the instrument to the trunk of a little tree beside his camp and had
reconnected it by extension wires. He ran his ground wire down into
the water of the reservoir. He remembered his experience in trying
to hold up a receiver for two or three hours and made a crude wire
sling to hold it. Thus equipped like a telephone central he could
listen indefinitely without inconvenience.
His new home satisfactorily furnished and equipped with all the
modern conveniences, he set out to make a more comprehensive
examination of the reservoir. There were a number of small streams
running into it. During the heat of the day when the sun shone
warm on the ice-capped peaks and melted the drifting snow in the
deep packed cañons these streams delivered a considerable volume
of water, but in the cool of the night they shrunk to a mere trickle,
some of them ceasing to flow altogether.
Scott followed one of the larger ones away back and up to its
hidden sources. He found side cañons packed with snow to the very
rims and out of the bottom of each there trickled a tiny stream of ice
cold water. In other places there were miniature glaciers thrusting
their icy beaks out into the main cañon and melting as they
advanced. The snow in the open was pretty well gone and there
seemed to be little danger of a flood from those frozen reservoirs
hidden so effectually from the direct rays of the sun.
There was only one great danger. Rain!
A heavy rainstorm on those barren peaks would inevitably mean
an overwhelming flood. Most of the watershed was bare rock and
there was very little vegetation to hold the rush of the assembled
waters from the smooth worn channels of the ancient streams. Nor
were there any pools or backwaters to delay the floods; nearly all
were straight, narrow chutes leading to the reservoir below.
“One good thunder storm like we have at home,” Scott thought,
“would spill the water over the top of that dam before a fellow had a
chance to open the flood gates; but they don’t have them here, it
just snows summer and winter.” And so it did as a rule. Only a storm
on an exceptionally warm day would produce rain at that altitude.
He climbed one of the lower peaks and there, perched on a block
of old volcanic rock, he had the whole country laid out before him.
The group of old Benny’s lookout, which had seemed so high on the
ridge above the valley cliffs, lay far below him. He could see the line
of the cliffs and the fringe of trees along the stream in the main
valley. A jutting rock was all that cut off the view of the town. The
reservoir looked like a toy lake on the stage. There was quite a
breeze up there on the rocks, but not a ripple marred the reflections
on the surface of the pond. He could even see Jed feeding
peacefully in the little meadow which appeared like a splotch of
bright green paint spilled in the middle of an otherwise sombre
picture. There was no limit to the view.
He searched all those miles of country within his vision for
another moving object; there was none to be seen. He heaved a
little sigh of relief and wondered when the time would come that he
would be freed from the anxiety of watching for that pursuing
shadow. It had been haunting him less than twenty-four hours, but
they seemed to him like an eternity.
However, the worry had not yet affected his appetite and he
started for the camp. He had climbed farther than he had realized. It
took almost an hour of steady climbing to get down to the reservoir.
He approached the camp cautiously but there was no trace of any
one having been there and a nicker of welcome from the meadow
told him that all was well with Jed. He ate his supper in comfort, put
on his improvised head gear, and settled back against a mossy rock
to listen to the gossip of the evening.
He watched the shadows chase the retreating sunlight up the
eastern peaks and saw those shadows slowly deepen into darkness
as the short twilight faded and disappeared. The world had gone to
sleep and there came to his ear on the hushed night air the tinkling
trickle of the little mountain streams and the plash of the water
dripping through the dam. Suddenly the tips of the western peaks
glowed white and the shadows came slowly down before the silver
rays of the rising moon.
And not a word from the telephone. Either the people were
unusually silent to-night or he had made some mistake in
reconnecting his instrument. He was half dozing now, gazing
dreamily at the moon herself balanced on the rim of the eastern
peaks when he heard a faint click. It might have been the click of a
receiver on the line or it might have been the cocking of a revolver.
Scott was wide awake now, as wide awake as he had ever been in
all his life. He had been asleep and had that dreaded shadow stolen
on him unawares, or was it only the telephone line? He had been too
nearly asleep to know. For the next few minutes he sat with every
sense alert and nerves on edge while he searched every shadow
with anxious eye and listened in vain for the slightest suspicious
sound. With a second slight click in the receiver he relaxed with a
gasp of relief that could have been heard at the other end of the line
if he had been anywhere near the transmitter.
It was another of those silent calls such as he had intercepted
once before. He would have sworn that there were two men on that
line now waiting to see if they had a clear field.
“Benson?” Scott recognized Dawson’s voice. Benson was the
grouchy clerk in the supervisor’s office. So he belonged to the ring!
Scott was glad of it; he had never liked the man but this was the
first evidence that he had discovered against him.
“Well?” came the answer after a pause.
“Where did they assign the boob?”
“To watch the dam. Tried to tell you last night.”
“Dugan and I were calling on him then.”
“Going up?”
“To-morrow.”
“Shoot one for me.”
Two soft clicks and all was still.
So Mr. Dawson was coming to call in the morning. Well, Scott was
glad to know it. Moreover, it made him feel that he was fairly safe
from any visitors before that time. With this assurance he rolled in
his blanket and went to sleep.
CHAPTER XVII

AN ATTEMPT AT BRIBERY

Scott awoke in the morning with a feeling of expectancy like a


boy who has promised himself when he went to sleep that he would
go fishing at four o’clock. He lay there drowsily for a moment
watching the western peaks catch fire from the rays of the rising
sun, and wondering vaguely what it was that he was going to do.
His eyes rested for an instant on the telephone and he sat up with a
jerk, awake to the situation.
He looked cautiously out over the dam and the cañon trail. It was
not likely that Dawson would come so early in the morning. He did
not know that Scott knew anything of his attempt to shoot him at
the cabin and had no reason to believe that he would be expected at
the dam. So there was no reason why he should come so early, but
Scott intended to be prepared for him. He bridled Jed and led him
over to the side of the meadow farthest from the trail and tied him
back of a large clump of willows. He hid the saddle in a thicket near
the trail.
He cooked his breakfast in the open with the receiver to his ear
for he suspected that Baxter was on the lookout down below and
might try to warn him. He was not nervous and excited as he had
been that night at his own cabin, because he knew what was coming
and felt prepared for it. Moreover, it was daylight and he was located
so that he could see the only road of approach for some distance.
There was no chance for an unexpected shot from an unseen foe.
It would have been easy enough to sneak back into the hills. He
could elude an army up there among those crags where he had
climbed the day before. But what good would it do? He could not
wipe out the traces of his presence at the dam, he could not even
make it appear that he had finished his business and left. He had
made but a one way trail in the cañon and it would be an easy
matter to find Jed even if he was hidden from sight.
No, there was nothing to gain by taking to the hills. He had been
hunted long enough. He would stay and fight it out. He realized that
being unarmed he would be at a tremendous disadvantage, but he
thought he could manage it if he had the chance to plan the meeting
as he wanted it. It was a desperate chance, but after his past
experience he felt that no chance would be too desperate to escape
becoming a hunted creature again, uncertain what danger might be
threatening him next. He planned just what he would do in every
contingency he could think of and had worked out everything so
nearly to his own satisfaction that he was not in the least rattled
when the telephone rang his own call at his district headquarters. He
answered it promptly.
“This is Baxter. Benny reported Dawson going your way at nine-
thirty. Somebody must have spilled the beans. Are you ready for
him?”
“Sure,” Scott answered with even more confidence than he really
felt.
“Good. Then go to it. So long.”
Scott took off his head gear and laid it aside. He glanced at his
watch. It was ten fifteen. His visitor ought to arrive about eleven-
thirty or possibly a little earlier if he was in a hurry. Scott went
carefully over his plans once more to see if he could think of
anything that he had overlooked. Then he settled down to watch the
trail.
He was not at all nervous. He was waiting for something definite;
he knew what it was, where it was coming from, and approximately
when it would arrive. Moreover, he felt prepared to meet it. There
was the same tense feeling of expectancy that he had often
experienced when he was waiting for the opening of a boxing
match, but no nervous shivers and no trace of fear.
It was a beautiful day. There were a few small clouds high up and
moving slowly that cast a patch of shadow here and there on the
broad landscape, but for the most part the sun shone brightly. A
strange day Scott thought for a man to start out to commit a
murder. Murders had always been associated with storms in the
books he had read, and it was hard for him to think seriously of it on
such a day as this. As the sun rose higher the little streamlets on the
other side of the reservoir began to increase in volume and babble a
little louder. All seemed peaceful. There was no place in that valley
for strife and violence; and yet he knew that every tick of the watch
was bringing it nearer.
His eye followed the shadow of a cloud slowly up the cañon slope
till it disappeared over the ridge. When he looked back at the trail
there was a horseman in full view. It did not startle him; it was what
he had been waiting for, and he had a feeling of real satisfaction
when he recognized Dawson. It would take him ten minutes more to
arrive and he could watch him for at least half of that time.
Dawson did not act like a man who was bent on murder, at least
he did not act as Dugan had that night at the cabin, and that was
the only real experience that Scott had had. He was riding along the
middle of the trail as he had always ridden about his work, with no
pretense at secrecy and no attempt at silence. On he came in broad
daylight as openly as he would have ridden to a wedding. Already
the clatter of his horse’s iron-clad hoofs on the loose stones of the
trail was plainly audible. Surely this man could be on no business of
which he was ashamed.
When horse and rider disappeared in a willow thicket just beyond
the lower end of the pasture Scott stepped quickly from his hiding
place and took up his position behind a large rock which lay near the
cabin and close beside the trail. He had no idea of avoiding this
man, but he wanted to pick his own meeting place and have him
within easy reach of his hand when he was discovered. Only in that
way could he hope to have a fair chance with that revolver. He could
see through a screen of brushes beside the rock and watch his
visitor after he entered the meadow.
The horse stopped on the edge of the meadow and breathed in
the smell of the lush grass with deep noisy breaths through wide
distended nostrils. It was something to which he was little
accustomed. The delay seemed to suit the master’s mood. He sat
idly in his saddle, apparently fascinated as Scott had been by the
grandeur and peaceful beauty of the scene.
His eyes were not searching the cabin and the immediate vicinity
for a hunted man. He was gazing dreamily back into those encircling
peaks and rugged, picturesque cañons. Even at that distance Scott
could see a pensive sadness in his expression. Any one who had
ever had business dealings with him in the past would have been
amazed to know that at that moment he would have been willing to
trade all his ill gotten gains to be freed from the burden of his crimes
and be able to roam those mountains once again as an honest man.
He loved those barren peaks and rocky cañons. He knew every rock
and tree and bunch of grass in all that countryside. They had been
his life. And now he realized too late that he had risked and maybe
lost it all for the sake of something he did not need.
He sat still so long that even his horse stopped cropping the
luscious grass and turned his head to look at him inquiringly. Scott,
too, was becoming uneasy. Could he have anything to fear from a
man who gazed at the beauty of the hills like that? It did not seem
possible, but he could not afford to take any chances and
determined to be on his guard just as he had planned.
Dawson seemed to be coming slowly to himself. He had been
dreaming of what might have been. He was more of a sentimentalist
than even his friends had ever realized but was also somewhat of a
philosopher. What was gone was gone and he must make the best of
what was left. Nor would he let any one interfere with his success.
The dreamy pensive look was gone now and in its place was the
gleam of a hard determination which had made men say that when
Dawson wanted anything bad enough he always got it.
He looked sharply about him, shook himself together and rode
straight across the meadow to the foot of the dam. He dismounted
and climbed the foot trail which led up past the end of the cabin.
Scott tried to forget the man he had seen a moment before. He
thought only of the look of hatred that this man had given him when
he had accused him by the valley cliffs, and that he was the self-
confessed companion of Dugan on that horrible night visit to the
cabin. He thought of that man and waited for him with every sense
alive to the danger of the situation, and prepared for immediate
action.
Dawson came on straight up the trail and headed for the cabin
without the slightest hesitation. Whatever might be his own
intentions he did not seem to have the slightest misgiving about the
other fellow’s. When he passed the big rock Scott stepped quickly
into the trail immediately behind him.
“Looking for me?” he asked sharply. He was ready to spring upon
the man at the first sign of a hostile move.
Dawson turned quickly. “So there you are,” he exclaimed. “Yes, I
was looking for you and I have had the deuce of a time finding you.”
He seemed perfectly at ease and not in the least taken back by
Scott’s sudden appearance.
“I was transferred up here yesterday morning,” Scott explained.
He thought maybe Dawson’s curiosity to know what had become of
him the night before that would show itself, but it had no effect.
“So I found out later,” he admitted so frankly that Scott wondered
whether he really could have been with Dugan, or whether he could
possibly have mistaken the voice on the ’phone the night before.
“Let’s sit down, I have a lot of things I want to talk over with
you,” and without waiting for an answer he sat down on the ground
with his back against the great rock and his face toward the rugged
mountain peaks. Scott accepted the invitation but carefully selected
a position where he would still be within easy reach of Dawson’s
pistol arm.
“I could sit here for a week and look at that view,” Dawson said
wistfully, and the dreamy look was stealing into his face again, “but
that’s not what I came for,” he added, bracing himself up quickly.
“That was a clever job you did in ferreting out those extra sheep. I
don’t know where in the thunder you got onto all that stuff, but you
seemed to be able to produce the goods. However, I think you
overreached yourself a little and made some statements which you
can never prove.”
“I think I was careful not to say anything which was not true,”
Scott replied cautiously.
“Possibly you were, but stating a truth is one thing and proving it
is often something different.”
“I think that I can prove them,” Scott said quietly.
“Well, I doubt it. Now let’s admit for the sake of the argument
that all the statements you made were true, excepting, of course,
your ability to prove them. You proved that there were more sheep
than there were permits, but you did not prove how they got on the
forest. Your inference is that Dugan let them through that hole in the
fence while he was counting the others through the chute. But you
can’t prove it. Maybe he put them all through the fence without
counting them, but there was no one there to see it. Your evidence
is entirely circumstantial and would not stand in any court.
“You said that I was a partner of Jed’s and directed all the
scullduggery. That is hardly likely, but suppose that it were true. You
can’t prove it. You think that I recommended Dugan’s appointment,
but I didn’t. He was assigned to us by the district office and nobody
on the forest had anything to say about it. You may say that I had
the district office appoint him, but you can’t prove it. There is no
proof that I am Jed Clark’s partner. It does not exist. You may know
—it beats me how you found it out if you do, but you may know—
that I hold a mortgage on Jed’s ranch. Even that would be hard to
prove for the mortgage is not recorded. But a mortgage is no proof
of partnership or even of complicity.
“You have woven a web of circumstantial evidence around me
that looks bad. It would not stand in a court of law for a minute, but
it will look nasty and will ruin my reputation. It will not do you any
good to lose out in the law suit. In fact it may harm you with a lot of
people because it will look as though you were trying to slip
something over on me to push your own advancement. Of course
you want to make good. You want to clean up this crooked business
and make the best showing that you can. But I do not believe that
you want to ruin a man for nothing.”
“You are perfectly safe in thinking that,” Scott said. He thought
that Dawson was trying to pump him to see what information he
really had. Yet, the ranger was not asking many questions or giving
him much chance to talk. He could not make out just what the game
was. It was too deep for him.
“I thought so,” Dawson said resuming his story. “When I first
came to this country ten years ago I had lived on the prairies all my
life and hated them. They were so flat that you could look till your
eyes ached and not see anything. The wind blew from one week’s
end to the next and there was no getting away from it. I fell in love
with these old mountains as soon as I laid eyes on them and I would
have taken any job which would have given me a chance to be in
them and live. This forest service job was better than that. It gave
me a home in the heart of the mountains, a good living and a little
more. I had a good business head and I invested my savings in
sheep. I was successful and amassed a small capital. I could have
left the service and made a fortune in sheep, but I liked the
mountains too well to leave them for wealth. I accumulated
considerable property more as mental exercise than anything else. I
had no use for the money and would not leave the mountains and
this outdoor life for any amount of wealth.
“So you see what my life here and my reputation mean to me and
how little I care for the money I have made. You on the other hand
are a young man, probably seeking your fortune in any field that
shows the best chances. There is big money in sheep for the man
who will devote his life to it.
“I have tried to show you what this life means to me. I think I
have shown you how utterly impossible it would be for you to prove
your case. You will only succeed in ruining me without helping either
yourself or the service.”
“I can’t agree with you,” Scott said, “because I think that I can
prove all those things.” The man talked so frankly and pled so
earnestly that it was hard to believe him utterly false. Scott began
reviewing his evidence to see if it was really as purely circumstantial
as Dawson had said it was.
Dawson looked at him keenly and thought that he was wavering.
“Drop this impossible charge against me,” he said suddenly, “and all
my accumulations of the past ten years are yours.”
So that was his game? All this smooth story was but the craftily
laid background for the offering of a bribe. He was taking the last
desperate chance of buying himself out of a hole which he knew to
be otherwise hopeless.
Scott’s growing sympathy turned instantly to disgust. “You can’t
bribe me,” he sneered contemptuously, “any more than your hired
cutthroat could bluff me.”
The change in Dawson was instantaneous. The look of
sentimental pleading was gone and his eyes flamed with malignant
hatred. So sudden and violent was his fury that Scott involuntarily
recoiled before it. Dawson sprang to his feet, out of reach, and drew
his revolver.
“Fool,” he hissed between his clenched teeth, “you are too good
for this world.”
The neighing of a horse in the meadow below stayed his hand for
an instant. Furious as he was he realized that he would gain nothing
if he freed himself from the charge of being a crook only to be
branded as a murderer. He cast a hurried glance toward the
meadow.
In that instant Scott hurled himself upon him. He struck up the
revolver with his left hand and followed through to Dawson’s chin
with his right. The report of the revolver dazed him and the sight of
the barrel pointed at his breast had almost made him sick, but he
struck that blow with all the desperation of a dying man backed by
years of training. Dawson sank down without a sound.
Scott stood dazed for a second hardly knowing what had
happened. He half thought that he had been shot. The sight of the
smoking revolver still grasped in Dawson’s fingers brought him to his
senses with a jerk. He flung himself upon the gun and snatched it
from the unresisting hand. He took off Dawson’s belt, turned him
over on his face, and bound his wrists together with the belt. He
slipped the holster onto his own belt and dropped the pistol into it.
One such experience was enough. He knew now how helpless an
unarmed man was. He hated a gun but he never wanted to be taken
at such a disadvantage again. The vision of the muzzle of that
“forty-five” would always be with him if he lived to be a thousand.
The hot sun was blazing down on the unconscious man and Scott
dragged him into the shade of the aspens beside the camp. He was
trembling from head to foot and now that the excitement was over
he felt so weak that he was glad to sit down in the shade and try to
think.
He looked out once more across the peaceful waters of the
reservoir at those stately guardian peaks and shuddered to think
how near he had been a few minutes before to losing his beautiful
world forever.
CHAPTER XVIII

A STORM AND A MADMAN

Scott sat for some minutes gazing absently at the rugged


mountains. He felt tired and his mind wandered listlessly from one
vague something to another, none of them connected with the
present situation. The peace and quiet of his surroundings began to
soak into him and a lassitude crept over him. He had been under a
much greater nervous strain than he had realized and the reaction
made him sleepy. He wanted to curl up right where he was and
sleep. He had no interest in anything else. His heavy eyes closed
wearily and he sank down beside the still unconscious man.
Scott dreamed that he was lying on the battlefield with other
wounded and dying men groaning all around him. The ambulance
corps picked him up and carried him far back of the lines to a
peaceful little French village surrounded by high mountains and put
him in a little cabin beside a lake. He could hear the babbling of
many small streams and the gentle lapping of tiny waves on a
pebbly shore. They were soothing, lulling sounds but woven through
them he could still hear the groans of the dying. The cabin was
becoming unbearably warm and oppressive. He writhed about on his
burning couch until the discomfort awoke him.
The groaning continued and Scott sat up suddenly to find that
Dawson had regained consciousness. His jaw was badly broken, and
it was his moaning that Scott had heard in his dreams. The sun was
shining directly on them both with a blistering heat unusual for that
time of the year. Scott did not know how long he had been asleep
but it must have been a long time. The sun had shifted to the
western half of the sky, a warm breeze was ruffling the surface of
the reservoir, and black clouds were peeping over the horizon.
Dawson was half delirious from suffering and lack of water in the
blazing sun. He was moaning constantly and talking incoherently. He
did not seem to recognize Scott or to know where he was.
Scott picked up the suffering man as carefully as he could and
carried him into the cabin. All his feeling against Dawson was gone
now and he saw only a human being in agony. He reproached
himself for going to sleep and leaving him in such a condition. He
realized now how panic-stricken he must have been to bind the
wrists of a crippled man when he himself was armed with the
cripple’s revolver. He removed the belt from Dawson’s wrists and ran
out to get some water from the reservoir. He poured some of it on
the parched lips and the injured man swallowed eagerly though
every movement of his mouth seemed to cause new agony. Scott
bathed his fevered brow, gave him a little more water to drink and
then bound up his jaw with his handkerchief. He wondered how he
could get him home. There were two horses there now, but Jed was
not well enough trained to be trusted with one end of a stretcher. A
trailing pole stretcher on Dawson’s horse would be too rough. He
decided that his best move would be to ’phone down to Baxter or
Benny for help.
His anxiety to aid the suffering man had so completely occupied
Scott’s attention that he had not noticed what was going on outside.
A sudden gust of wind forced his attention. He ran to the door. The
little black clouds which were just peeping over the horizon a short
time before had spread over half the sky. The heat was oppressive
and a warm, sultry wind which was blowing half a gale seemed only
to accentuate it. Angry little waves were beating on the shore now
and the growing streams on the other side of the reservoir were
beginning to roar ominously.
Scott ran down to the edge of the reservoir to look at the mark he
had set on the dam the day before. The water had already risen a
foot since he had noticed it that morning and he knew from the rush
of waters in the cañons that it was rising now at an alarming rate.
He glanced at his watch. It was five o’clock. Ordinarily the cool of
the approaching evening had begun to tie up the springs of ice and
snow in the hidden cañons before that time and the streams would
be drying up, but to-day that hot wind was searching its way into
every cranny of the rocks and melting the winter’s store of ice at a
tremendous rate. Nor would they cease to melt even with the setting
of the sun as long as that wind continued. A warm rain on top of
that was almost sure to be disastrous.
Even while Scott looked the last patch of blue was blotted from
the sky and the little basin was thrown into semi-darkness. The
swiftness of the onrushing storm was bewildering. He would ’phone
Baxter for help to get Dawson out of there and then open the sluice
gates without waiting for the level of the reservoir to reach the
danger point. He feared that it would reach it all too quickly even
with the sluice gates open.
Scott rushed up the bank to the little camp and grabbed the
telephone. He gave Baxter’s ring and waited what seemed an age.
He tried three times without getting any answer. Baxter must be
either out on the range or out of hearing of the ’phone. He tried
Benny. Benny was always there.
“Hello,” came the prompt answer.
“That you, Benny? This is—”
He was interrupted by a blinding flash followed instantly by a
deafening explosion. The receiver was apparently wrenched from his
hand and he stood dazed while the reverberations of the mighty
report were hurled crashing from peak to peak. The storm was on
them. He grasped the ’phone again desperately but the fuses were
burned out and the line was dead.
The echoes of the first crash of thunder had not died away in the
distant hills when the rain came down in torrents. A half hour of that
and the reservoir would overflow even if the dam itself did not go
out before that. The opening of the sluice gates was the only thing
which he could do. He could not imagine those sluice gates taking
care of the mad torrents which would soon be raging down the
cañons from all those encircling barren peaks, but the storm might
possibly cease as suddenly as it had begun.
Scott sprang to the gates and was already bending his back to the
old-fashioned windlass when he remembered that Jed was on the
other side of the meadow. Once he had opened those gates it would
be impossible to get him across to the trail. He had to have Jed to
get help for Dawson and carry the warning of the impending danger
to the ranchers along the course that the flood would take if the
dam should burst.
The rain continued to fall in a deluge which almost blinded him,
but he managed to stagger across the meadow to the clump of
willows where he had left Jed. He feared that the horse might have
been frightened by the storm and run away. The booming of the
thunder in those hollow cañons was enough to terrify either horse or
man. But Jed had spent his life in the open. Thunder storms in the
mountains were nothing new to him. Close in the lee of the bushes,
with his tail to the storm, he was waiting patiently. He greeted Scott
with a little nicker of recognition.
Scott jumped on to his slippery, wet back and rode across the
darkening meadow toward the place where he had hidden the
saddle. He put on the saddle while there was yet light and leaving
Jed well up from the trail, he dashed once more for the sluice gates.
In the trail at the foot of the dam he almost ran into a strange horse.
The poor beast was saddled and bridled and steaming in the rain
from hard riding. Its breath was coming in great gasps, its head
hung down until its nose was almost on the ground, and its feet
were spread wide, a sign of total exhaustion. Some one had ridden
up that steep cañon trail at a killing pace.
“It must be Baxter,” Scott thought as he ran past the heaving
horse and made for the sluice gates. There was not enough daylight
left to recognize objects at any distance, but almost continuous
lightning flashes made things stand out momentarily with vivid
distinctness. Scott was just rounding a clump of bushes not more
than ten yards from the sluice gates, when one of these lurid flashes
revealed a picture which brought him to a sudden halt with his heart
in his mouth.
Seated on top of the sluice gates was not Baxter, but Jed Clark.
He was crazy with drink. He was holding a forty-five in either
hand. After every flash of lightning he waved the revolvers wildly in
the air and shouted his vengeance against the forest service, the
government and all law in general. He seemed to revel in the
wildness of the storm. He was raving mad.
Scott stood as one stunned. He was in the shadow of the bushes
and Jed had not seen him. He knew that Jed had come up there
with the original intention of getting him. Failing to find Scott his
crazed brain had now hit on the still more devilish scheme of reeking
his vengeance on the forest service by bringing about the
destruction of the dam. None knew the country better than he. None
knew better than he how impossible it would be for that old dam to
withstand the flood which was gathering against it. Now utterly
regardless of his own danger he was seated on the sluice gates of
the very dam he was planning to destroy, recklessly chanting his
vengeance in the face of the raging elements.
The whole thing seemed so fiendish, so utterly inhuman, that
Scott stared helplessly for a moment in an agony of dismay. His first
impulse was to rush the maniac, for the gates must be opened and
that quickly. But he gave up the idea almost as soon as he conceived
it. Jed was well known to be a dead shot, drunk or sober, and the
experience of the morning had shown Scott how perfectly helpless
he would be.
There was only one way out. Dawson’s revolver. It had been in his
way when he was ministering to Dawson’s hurts and he had taken it
off. He started for the cabin and it suddenly occurred to him that Jed
would have gone there the first thing. He remembered the
unrecorded mortgage and Jed’s veiled threat at that night meeting
below the chute. He trembled to think what he might find in the
cabin. Shivering he groped his way across the room to the bed. He
leaned over it and waited for the next flash of lightning. It came and
the frozen look of horror in the wide staring eyes of the man before
him made his blood run cold. He wanted to run from the cabin but
Dawson grabbed him by the sleeve. He tried to tell Scott something
but the mumbled words from the tightly bound jaws were lost in the
raging of the storm.
Scott realized that Jed had been to the cabin. He apparently had
not in his drunken search noticed Dawson, but the injured man,
helpless as he was, had been dreading his return. When Scott
leaned over him he had thought that it was Jed and felt that his time
had come. He held onto Scott now until the next flash could show
him pointing to the dam. “Jed,” he tried to say between his closed
teeth.
Scott understood. He leaned close to Dawson’s ear and shouted
above the booming of the storm, “I saw him. I’m going after him
now.”
He picked up the revolver from the table and started out of the
cabin. The last of the daylight was gone now and the frequent
flashes of blinding lightning were separated by short periods of
Stygian darkness. The recurring echoes of one mighty crash of
thunder never died away till there was another crash that seemed
louder yet. The effect was cumulative. It was as though all the
storms of the ages had been dumped into that little caldron in the
midst of the mountain peaks.
If the ground had been more familiar it would have been an easy
matter for Scott to have utilized the lightning flashes to locate the
next patch of shelter and to have run to it in the ensuing darkness,
but he had not been there long enough for that. The vivid flashes
confused him and everything looked strange in the weird light. It did
not matter how much noise he made for nothing would be heard
above the storm but he had to keep under cover for the lightning
made objects stand out with uncanny clearness.
He trembled to think what he was going to do. It seemed the
irony of fate that he, who had always shunned the use of a revolver
and shuddered at the thought of shooting a man even in the heat of
action, should now be called upon to shoot a man in cold blood. But
there was nothing else to do. The lives of women and children in the
valley below hung on the chance of getting that maniac away from
the sluice gates. Scott accepted the call of fate, closed his senses to
his own feelings, and crept on with unwavering determination. His
mind was made up. He would shoot this man as he would shoot a
mad dog to save the lives of others.
He had made his way almost to the clump of bushes where he
had first discovered Jed—he had to get close or he knew that he
would miss—when a flash of lightning revealed another object
crawling around that same clump of bushes. Surprised as he was he
recognized it even in that brief flash. He recognized the cautious
snake-like crawl, and that gleaming steel. It had been graven on his
memory that evening at the cabin when he had sat in the shadow of
the forest and watched that same snake-like object crawl toward his
cabin window. He could recognize it instantly anywhere.
But what was Dugan doing there at this out-of-the-way dam in a
raging storm, and crawling inch by inch with a gun in hand toward
the man who had been his friend? Either he had not recognized Jed
and thought that he was stalking Scott, or had some ulterior motive
which Scott did not know anything about for disposing of Jed. It was
probably the former. Scott noticed that Jed was no longer
brandishing his guns and shouting curses in the teeth of the storm.
A fit of sullen depression had apparently come over him and he was
crouched in a heap so that it was difficult even to recognize him as a
man, to say nothing of determining his identity.
Dugan evidently wanted to make sure. He could easily have
picked the man off from where he was, but he wormed his way
steadily nearer. He was beyond the last piece of cover now and was
working his way across the narrow open space which separated him
from the sluice gates of the dam.
The storm instead of abating seemed to be increasing in fury.
Flash followed flash almost without cessation. The crashing of the
thunder sounded like a barrage of hundreds of big guns. And
through it all there sounded the rush of waters. There seemed to be
but one inanimate object in the whole scene. Trees and rocks and
mountain peaks seemed to be dancing in the fickle flashes of light.
The man on the sluice gates only seemed motionless. Perhaps he
had gone to sleep in that perilous position on those groaning sluice
gates.
Scott watched with a curious fascination. It seemed to him that
fate had thought better of her irony and was sending this special
agent to relieve him of his odious task. He was perfectly willing to
have it so. It was like a reprieve from a horrible sentence. It had but
one disagreeable feature. It was so maddeningly slow. He dreaded
lest he should hear the dam giving way almost any minute.
Dugan did not seem to be in any hurry. He wanted to make sure.
He evidently doubted whether the motionless object on the sluice
gates was his man. He was lying perfectly still now watching it. He
did not want to risk a shot at a scarecrow and sound a warning.
Convinced at last that he was mistaken he rose to his feet and took
a step toward the sluice gates.
There was a spit of flame, the roar of a forty-five, accompanied
by a mocking laugh from the motionless object on the sluice gates,
and Dugan staggered. He was hard hit but he was not the man to
go alone. He steadied himself. There were two more reports almost
simultaneously and the flashes from the two revolvers almost met.
Jed pitched backwards into the deep boiling waters of the
reservoir and Dugan sank silently beside the sluice gates. Fate
worked it out without Scott’s aid.
CHAPTER XIX

THE BURSTING OF THE DAM

There was no time to waste in mourning over the fate of the two
outlaws. Scott’s first duty was to the unsuspecting ranchers in the
path of the coming flood. The waves were already washing over the
top of the dam and the old sluice gates were groaning under the
strain. The storm still raged in unabated fury. Everywhere there was
running water. It was coming down the face of the rocky slopes in
sheets and all the cañons were filled with boiling torrents. The roar
of it sounded like a mighty accompaniment to the booming of the
thunder.
Before the echoes of the pistol shots had been swallowed up in
the other noises of the storm Scott sprang for the windlass, but he
was too late. Jed Clark was dead but he had accomplished his crazy
purpose. With a crash and rending of heavy timbers the sluice gates
went out on the crest of the flood and carried a small portion of the
dam with them. The whole structure trembled from end to end.
Scott felt the mason work crumbling under his feet and the swirling
waters grasping at his ankles. He scrambled desperately out of its
clutches and rushed to the place where he had left Jed. He was
gone, but a frightened snort from higher up the steep side of the
cañon led him to where the terrified horse had climbed to the base
of the perpendicular wall of rock and stood trembling, too frightened
to move.
The one chance now was to beat out the flood. To reach the
ranchers in the valley below before the wall of water which would
come when the dam went out, and that could be only the matter of
minutes now. It was a desperate chance, for the trail was steep and
rough, and the rush of the waters would make it almost impassable
in places.
Scott flung himself onto Jed’s trembling back and turned him
down the cañon trail. Another crash in the direction of the dam sent
him plunging ahead, and once started a mad fright took possession
of him. He ran like a fiend. Scott had learned much about riding
since he had cleared the corral fence clinging to Jed’s neck, but it
required all his skill to stay in the saddle now. He had to close his
eyes to protect them from the twigs which slashed his face, and
once a jagged point of rock grazed his knee and almost threw him
from the horse’s back.
“It’s up to you, Jed, old boy,” Scott whispered in the horse’s ear, “I
can’t help you any now.”
The roar of the torrent was always with him. Now the trail dipped
down to its very edge, into it once; now it climbed high on the side
of the cañon and skirted a narrow ledge at the edge of a wall of
rock. The hollow booming of the waters hinted of sickening depths
within easy reach of a misplaced foot. It seemed marvelous to Scott
that Jed could run at that breakneck speed on such rugged ground,
but the horse had been born in the mountains, had raced over them
all his life, and he never stumbled.
He was gaining on the flood. Already he had passed the crest of
the wave from the shattered sluice gates. There was water in the
stream, plenty of it, from the drainage below the dam, but it was not
the raging torrent which it had been higher up. The storm was
lessening now. A star or two were peeping through the rifts in the
black clouds and the profiles of the mountains were beginning to
loom in darker shadows. Scott recognized the ridge ahead where the
lookout station was located. He had to turn to the left there and
follow the valley instead of going up over the pass the way he had
come. From there on the country was wholly new to him and he
would have to trust entirely to Jed. He wondered whether he ought
to try to stop at the station and get Benny to telephone the news.
A dull roar like the rumble of distant thunder shook the mountain
and Scott knew that the dam had given way. There was no time to
lose now. The rush of water from the sluice gates would be like a
dribble compared with the mighty avalanche of water which would
roar down the valley now. Moreover, Jed was not yet under control
and he would do well if he could hold him in the valley trail, to say
nothing of stopping at Benny’s.
He began to talk soothingly to Jed and tried to steady him a little.
As he approached the turn in the valley he made out a figure
standing on the opposite edge of the stream. He recognized Benny
and tried to stop, but Jed was not yet ready to listen to reason. Scott
succeeded in turning him, probably because he did not want to cross
the stream, but he could not stop him. He had no control over him
at all.
“The dam is gone. Telephone,” he shouted at the top of his voice
as he rushed past. Either Benny did not understand or could do
nothing for he stood there quietly on the edge of the stream and
listened to the roar of the cañon.
The ground was more even here in the wider valley, and much
easier going for the horse. He had already covered five miles at that
terrific pace, and although it did not seem to be telling on his
splendid physique it seemed impossible for any animal to keep that
up for the remaining fifteen miles to the valley. Scott began to talk
to him once more. It was the only influence to which the big horse
had ever seemed susceptible. There was no longer the roar of the
water in the cañon to frighten him. There were not the same
deafening thunder crashes with their weird reverberations, the
rending of the gates was fading from his memory. Gradually Scott
could feel the straining effort lessening. He was still making splendid
time, but he was running more smoothly and he turned back his ear
to listen when Scott talked to him.
Four miles of that smooth running in the upper valley and then
down the steep trail to the main valley in which the town was
located. The trail came out to the plain near the home of the last
rancher whom Scott had gone to see about the free use permits. It
was here that the strange procession had ended that day. As Jed
shot out of the cañon into the open a man’s form darkened the
lighted doorway. Evidently he had heard the clatter of the rapidly
approaching hoofs on the rocky trail.
Scott slowed down and shouted, “The dam has burst. You better
beat it. Telephone the others.”
He loosened the rein and Jed sped on. The figure disappeared
instantly and looking back over his shoulder Scott could see the
lights bobbing about the house. It was a warning of disaster to those
people and they did not hesitate. It meant the destruction of their
homes and all of their possessions which they could not move to the
higher ground along the base of the valley cliffs.
At each of the other houses he had to stop and shout to get the
people out. They had had no warning. The whole telephone system
had been disabled by the storm. The message delivered, there was
no delay, no stopping to get an explanation. The men sprang silently
back to the houses and wasted none of the precious moments which
were left them. They had been living in dread of just this thing for
years and now it had come. They had been fearing it too long to be
in any doubt as to what to do now.
All along behind Scott men were fleeing from their homes as from
a pestilence with their families and most valuable possessions in
wagons and driving their stock before them. There was many a
backward glance at the homes which would probably be ruined
when they saw them again.
After each stop Scott watched Jed anxiously to see if he was in
distress but each time the noble animal took up his task willingly and
was soon back in his swinging run which sent the miles flying behind
him.
There was nothing ahead of him now but the town only two miles
away, and Jed was pounding over the level plain with hoof beats as
regular as the ticking of a watch. The town was all aglow with lights
and the people were busy with their everyday affairs, ignorant of the
impending danger.
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