100% found this document useful (4 votes)
80 views

PDF Building Applications with Scala 1st Edition Pacheco download

Applications

Uploaded by

ruchigrotzfn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
80 views

PDF Building Applications with Scala 1st Edition Pacheco download

Applications

Uploaded by

ruchigrotzfn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Building Applications with Scala 1st Edition Pacheco

_____ Click the link below to download _____


https://ebookgate.com/product/building-applications-
with-scala-1st-edition-pacheco/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Building High Integrity Applications with SPARK 1st


Edition John W. Mccormick

https://ebookgate.com/product/building-high-integrity-applications-
with-spark-1st-edition-john-w-mccormick/

ebookgate.com

Building B2B Applications with XML A Resource Guide 1st


Edition Michael Fitzgerald

https://ebookgate.com/product/building-b2b-applications-with-xml-a-
resource-guide-1st-edition-michael-fitzgerald/

ebookgate.com

Agile Data Science Building Data Analytics Applications


with Hadoop 1st Edition Russell Jurney

https://ebookgate.com/product/agile-data-science-building-data-
analytics-applications-with-hadoop-1st-edition-russell-jurney/

ebookgate.com

Getting Started with SBT for Scala 1st New edition Edition
Shiti Saxena

https://ebookgate.com/product/getting-started-with-sbt-for-scala-1st-
new-edition-edition-shiti-saxena/

ebookgate.com
Building Web Applications with ADO NET and XML Web
Services 1st Edition Richard Hundhausen

https://ebookgate.com/product/building-web-applications-with-ado-net-
and-xml-web-services-1st-edition-richard-hundhausen/

ebookgate.com

Building PHP Applications with Symfony CakePHP and Zend


Framework 1st Edition Bartosz Por■bski

https://ebookgate.com/product/building-php-applications-with-symfony-
cakephp-and-zend-framework-1st-edition-bartosz-porebski/

ebookgate.com

JavaTM Programming with CORBATM Advanced Techniques for


Building Distributed Applications 3rd Edition Gerald Brose

https://ebookgate.com/product/javatm-programming-with-corbatm-
advanced-techniques-for-building-distributed-applications-3rd-edition-
gerald-brose/
ebookgate.com

Scala Data Analysis Cookbook Navigate the world of data


analysis visualization and machine learning with over 100
hands on Scala recipes 1st Edition Arun Manivannan
https://ebookgate.com/product/scala-data-analysis-cookbook-navigate-
the-world-of-data-analysis-visualization-and-machine-learning-with-
over-100-hands-on-scala-recipes-1st-edition-arun-manivannan/
ebookgate.com

Professional Scala 1st Edition Janek Bogucki

https://ebookgate.com/product/professional-scala-1st-edition-janek-
bogucki/

ebookgate.com
Building Applications with Scala
Table of Contents
Building Applications with Scala
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Introduction to FP, Reactive, and Scala
Functional programming
Principles of functional programming
Immutability
Disciplined state
Pure functions and no side effects
First-class functions and higher-order functions
Type systems
Referential transparency
Installing Java 8 and Scala 2.11
Read Eval Print and Loop - REPL
Scala Hello World using the REPL
Scala REPL Hello World program
Scala object-oriented HelloWorld program
Scala HelloWorld App in the Scala REPL
Java HelloWorld application
Scala language - the basics
Scala variables - var and val
Scala REPL var usage
Scala val usage at the Scala REPL
Creating immutable variables
Scala variable type in the Scala REPL
Scala variables with explicit typing at the Scala REPL
Scala conditional and loops statements
If statements in Scala REPL
If statements in return statements in Scala REPL
Basic for loop in Scala REPL
For with List in Scala REPL
For with if statements for filtering - Scala REPL
Java code for filtering even numbers
For comprehensions
For comprehension in Scala REPL
Java code for performing filtering with collections
Scala collections
Creating, removing, and getting an item from a mutable list in Scala REPL
Scala tuples
Scala immutable Map in Scala REPL
Scala mutable Maps at Scala REPL
Monads
Scala Map function in Scala REPL
Option Monad in Scala
A list of all methods using the Scala REPL
Scala class, traits, and OO programming
A simple Scala class in Scala REPL
Scala plain old Java object in Scala REPL
Person class in Java
Traits and inheritance
Scala inheritance code in Scala REPL
Scala traits sample code in Scala REPL
Scala traits using variable mixing technique at Scala REPL
Scala type alias sample in Scala REPL
Case classes
Scala case classes feature in Scala REPL
Pattern Matcher
Simple Pattern Matcher in Scala
Advanced pattern matcher in Scala REPL
Advanced complex pattern matcher in Scala REPL
Partial functions
Simple Partial function in Scala REPL
Scala PartialFunction without OO using case statements in Scala REPL
PartialFunction composition in Scala REPL
Package objects
package.scala
MainApp.scala
Functions
Partial application
Partial function in Scala REPL
Curried functions
Curried functions - Scala REPL
Curried transformation in Scala REPL
Operator overloading
Scala operator overloading in Scala REPL
Implicits
Scala Implicits in SCALA REPL
Implicit Parameter at Scala REPL
Futures
Simple Future code in Scala REPL
A complete Future sample at Scala REPL
Reactive Programing and RxScala
Simple Observables Scala with RxScala
Simple Observables Scala with RxScala - Execution in the console
Complex Scala with RxScala Observables
Summary
2. Creating Your App Architecture and Bootstrapping with SBT
Introducing SBT
Installing SBT on Ubuntu Linux
Getting started with SBT
Adding dependencies
Generating Eclipse project files from SBT
Application distribution
Hello world SBT / Scala App
Bootstrapping our Play framework app with Activator
Activator shell
Activator - compiling, testing, and running
Summary
3. Developing the UI with Play Framework
Getting started
Creating our models
Creating routes
Creating our controllers
Working with services
Configuring the Guice module
Working with views(UI)
Summary
4. Developing Reactive Backing Services
Getting started with reactive programming
IPriceService - Scala trait
PriceService - RxScala PriceService implementation
Guice Injection - Module.scala
NGServiceEndpoint
Play framework and high CPU usage
RndDoubleGeneratorController
IRndService.scala - Scala trait
RndService.scala - RndService implementation
Module.scala - Guice Injections
main.scala.html
product_details.scala.html
Summary
5. Testing Your Application
Unit testing principles
Making code testable
Isolation and self-contained tests
Effective naming
Levels of testing
Testing with Junit
Behavior-Driven Development - BDD
MyFirstPlaySpec.scala - First BDD with ScalaTest and the Play framework
Testing with Play framework support
ProductService.scala - FIX the code issue
ImageServiceTestSpec.scala - ImageService Test
ReviewServiceTestSpec.scala - ReviewService test
Testing routes
RoutesTestingSpec.scala - Play framework route testing
Controller testing
RndDoubleGeneratorControllerTestSpec.scala - RndDoubleGeneratorController tests
IntegrationSpec.scala
ProductControllerTestSpec.scala
product_index.scala.html
ImageControllerTestSpec.scala
image_index.scala.html
ReviewControllerTestSpec.scala
review_index.scala.html
ApplicationSpec.scala
NGServiceImplTestSpec.scala
NGServiceEndpointControllerTest.scala
Summary
6. Persistence with Slick
Introducing the Slick framework
MySQL setup
Configuring Slick in our Play framework app
Configure the database connection
FPM Mapping
ProductDao
ReviewDAO
ImageDao
Slick evolutions
Refactoring services
Refactoring controllers
Configuring DAO packages in Guice
Refactoring tests
Generic mocks
Service tests
Controller tests
Running the application
Summary
7. Creating Reports
Introducing JasperReports
JasperReports workflow
Jasper sessions
Installing Jaspersoft Studio 6
Configuring MySQL Data Adapter in Jaspersoft Studio
Creating a product report
Creating a review report
Creating an image report
Integrating JasperReports with Play framework
build.sbt
Generic report builder
Adding the report to the product controller
Adding the report to the review controller
Adding the report to the image controller
Routes - adding new report routes
New centralized reports UI
Adding the report button for each view
Summary
8. Developing a Chat with Akka
Adding the new UI introduction to Akka
Introduction to the Actor model
What is an Actor?
Message exchange and mailboxes
Coding actors with Akka
Actor routing
Persistence
Creating our chat application
The chat protocol
The chat controller
Implementing the chat controller
Configuring the routes
Working on the UI
Adding Akka tests
Scala test for Akka Actor
Chat room Actor test
Chat Bot Admin Actor test
Summary
9. Design Your REST API
Introduction to REST
REST API design
HTTP verbs design
Uniform API
Response with HTTP status codes
REST API patterns
API versioning
Some anti-patterns to be avoided
Creating our API with REST and JSON
RestApiContoller
REST API Front Controller implementation
JSON mapping
Configuring new routes
Testing the API using the browser
Creating a Scala client
Configuring plugins.sbt
Configuring build.sbt
Scala client code
Creating our REST client proxies
Creating ScalaTest tests for the proxies
Adding back pressure
The leaky bucket algorithm
Scala leaky bucket implementation
Testing back pressure
Adding Swagger support
Swagger UI
Build and install Swagger Standalone
Summary
10. Scaling up
Standalone deploy
Reports folder
Changing report builder
Defining the secret
Running the standalone deploy
Architecture principles
Service orientation (SOA/microservices)
Performance
Scalability/Resiliency
Scalability principles
Vertical and horizontal scaling (up and out)
Caching
Load balancer
Throttling
Database cluster
Cloud computing/containers
Auto Scaling
A note about automation
Don't forget about telemetry
Reactive Drivers and discoverability
Mid-Tier load balancer, timeouts, Back pressure, and caching
Scaling up microservices with an Akka cluster
Scaling up the infrastructure with Docker and AWS cloud
Summary
Building Applications with Scala
Building Applications with Scala
Copyright © 2016 Packt Publishing

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

Every effort has been made in the preparation of this book to ensure the accuracy of the
information presented. However, the information contained in this book is sold without
warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or alleged to be caused directly or
indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals. However,
Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2016

Production reference: 1021216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-78646-148-3

www.packtpub.com
Credits
Author Copy Editor

Diego Pacheco Sonia Mathur

Reviewer Project Coordinator

Yuanhang Wang Suzanne Coutinho

Commissioning Editor Proofreader

Kunal Parikh Safis Editing

Acquisition Editor Indexer

Denim Pinto Tejal Daruwale Soni

Content Development Editor Graphics

Rohit Singh Jason Monteiro

Technical Editor Production Coordinator

Jijo Maliyekal Melwyn Dsa


About the Author
Diego Pacheco is an experienced software architect and DevOps practitioner with over 10
years of solid experience. He has led architecture teams using open source solutions such as
Java, Scala, Amazon Web Services (AWS), Akka, Apache Cassandra, Redis, ActiveMQ,
NetflixOSS Stack - Simian Army, RxJava, Karyon, Eureka, and Ribbon on cig customers in
Brazil, London, Barcelona, India, and the USA. Diego has a passion for functional
programming and is currently working as a software architect/agile coach with Scala, Akka,
and NetflixOSS. During his free time, he enjoys gaming, blogging, and playing wicked tunes
on his guitar. You can check out his blog at http://diego-pacheco.blogspot.in/.

Some of his core skills include the following:


Architecture design and architecture coding for high scalable systems
Distributed systems using SOA and microservices principles, tools, and techniques
Performance tuning and DevOps engineering
Functional programming and Scala
Agile coaching and servant leadership for architecture teams
Consultancy on development practices with XP/Kanban

More about him can be found at the following:


Linkedin: https://www.linkedin.com/in/diegopachecors
Blog: http://diego-pacheco.blogspot.in/
Github: https://github.com/diegopacheco
Slideshare: http://www.slideshare.net/diego.pacheco/presentations
Presentations: https://gist.github.com/diegopacheco/ad3e3804a5071ef219d1

His recent lectures include Netflix (https://www.youtube.com/watch?


v=Z4_rzsZd70o&feature=youtu.be), QCon (http://qconsp.com/sp2016/speaker/diego-
pacheco), and Amazon (http://www.meetup.com/Sao-Paulo-Amazon-Web-Services-AWS-
Meetup/events/229283010/).
Acknowledgments
First of all, I'm very thankful for everything God has given to me in life. So, I need to say
thank you to God at least three times. Thank you God, thank you God, thank you God. I’m
very glad to have finished this book, and I also need to say a big thank you to all my family
and supportive friends, especially Andressa Bicca, my true love; my mother, Denise Maris;
my grandmother, Walkyria; and my dear friends, Margarida Avila, Adão Avila, Israel Prestes,
and Tais da Rosa, for all their love and support. I need to say thanks to Packt, especially to
Kirk D'costa and Rohit Kumar Singh for being great editors. Also, I need to say thank you to
ilegra.com and especially to Ivã Boesing and Romulo Dornelles for all the space, trust, and
support. Also, I cannot forget to say thank you to my coworkers, customers, and friends, who
are great people to work with, and who I’ve learned a lot from: Sam Sgro, Daniel Wildt,
Anibal Rojas, Alexandre Poletto, Jeferson Machado, Nilseu Padilha, Jackson Santos,
Christophe Marchal, Joel Correa, and Rafael Souza. Finally, thank you to all of you who
bought this book and have read it--you are awesome!
About the Reviewer
Yuanhang Wang describes himself as an enthusiast of purely functional programming and
neural networks, with a primary focus on Domain Specific Language (DSL) design, and he
has dabbled in several functional programming languages. He is currently a data scientist at
China Mobile Research Center, working on a typed data processing engine and optimizer
built on top of several big data platforms.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub
files available? You can upgrade to the eBook version at www.PacktPub.com and as a print
book customer, you are entitled to a discount on the eBook copy. Get in touch with us
at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a
range of free newsletters and receive exclusive discounts and offers on Packt books and
eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt
books and video courses, as well as industry-leading tools to help you plan your personal
development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
Functional programming started in academia and ended up in the IT industry. The Scala
language is a multi-paradigm language used by big players and large organizations that helps
you get the correct (in the sense of pure functional programming) software and, at the same
time, software that is practical and scalable.

Scala has a very rich ecosystem, including Play Framework, Akka, Slick, Gatling, Finable,
and more. In this book, we will start right from the basic principles and ideas on functional
and ReactiveX programming, and through practical examples, you will learn how to code
with the most important frameworks of the Scala ecosystem, such as Play, Akka, and Slick.

You will learn how to bootstrap a Scala application with SBT and Activator, how to build a
Play and Akka application step by step, and we cover the theory of how to scale massive Scala
applications with cloud and the NetflixOSS stack. This book will help you to go from the
basic subjects to the most advanced ones in order to make you a Scala expert.
What this book covers
Chapter 1, Introduction to FP, Reactive, and Scala, looks at how to set up a Scala development
environment, the difference between functional programming and object-oriented
programming, and the concepts of functional programming.

Chapter 2, Creating Your App Architecture and Bootstrapping with SBT, discusses the overall
architecture, SBT basics, and how to create your own application.

Chapter 3, Developing the UI with Play Framework, covers the principles of web development
in Scala, creating our models, creating our views, and adding validations.

Chapter 4, Developing Reactive Backing Services, introduces you to reactive programming


principles, refactoring our controllers, and adding Rx Scala to our services.

Chapter 5, Testing Your Application, looks into testing principles with Scala and JUnit,
behavior-driven development principles, using ScalaTest specs and DSL in our tests, and
running our tests with SBT.

Chapter 6, Persistence with Slick, covers principles of database persistence with Slick,
working with Functional Relational Mapping in your application, creating the queries you
need with SQL support, and improving the code with async database operations.

Chapter 7, Creating Reports, helps you understand Jasper reports and add database reports to
your application.

Chapter 8, Developing a Chat with Akka, discusses the actor model, actor systems, actor
routing, and dispatchers.

Chapter 9, Design Your REST API, looks into REST and API design, creating our API with
REST and JSON, adding validations, adding backpressure, and creating a Scala client.

Chapter 10, Scaling Up, touches upon the architecture principles and scaling up the UI,
reactive drivers, and discoverability. It also covers middle-tier load balancers, timeouts, back
pressure, and caching, and guides you through scaling up microservices with an Akka cluster
and scaling up the infrastructure with Docker and AWS cloud.
What you need for this book
For this book, you will need the following:
Ubuntu Linux 14 or superior
Java 8 update 48 or superior
Scala 2.11.7
Typesafe Activator 1.3.9
Jasper Reports Designer
Windows fonts for Linux
Eclipse IDE
Who this book is for
This book is for professionals who want learn Scala, as well as functional and reactive
techniques. This book is mainly focused on software developers, engineers, and architects.
This is a practical book with practical code; however, we also have theory about functional
and reactive programming.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of
information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames,
dummy URLs, user input, and Twitter handles are shown as follows: "The next step is to
create the environment variable called SCALA_HOME, and to put the Scala binaries in the PATH
variable."

A block of code is set as follows:


package scalabook.javacode.chap1;

public class HelloWorld {


public static void main(String args[]){
System.out.println("Hellow World");
}
}

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


export JAVA_HOME=~/jdk1.8.0_77
export PATH=$PATH:$JAVA_HOME/bin

New terms and important words are shown in bold. Words that you see on the screen, for
example, in menus or dialog boxes, appear in the text like this: "The Actor behavior is the
code you will have inside your Actor."
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book--
what you liked or disliked. Reader feedback is important for us as it helps us develop titles
that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's
title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or
contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to
get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at
http://www.packtpub.com. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:


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

Once the file is downloaded, please make sure that you unzip or extract the folder using the
latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at


https://github.com/PacktPublishing/Building-Applications-with-Scala. We also have other
code bundles from our rich catalog of books and videos available at
https://github.com/PacktPublishing/. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used
in this book. The color images will help you better understand the changes in the output. You
can download this file from
https://www.packtpub.com/sites/default/files/downloads/BuildingApplicationswithScala_ColorImag
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen.
If you find a mistake in one of our books--maybe a mistake in the text or the code--we would
be grateful if you could report this to us. By doing so, you can save other readers from
frustration and help us improve subsequent versions of this book. If you find any errata,
please report them by visiting http://www.packtpub.com/submit-errata, selecting your book,
clicking on the Errata Submission Form link, and entering the details of your errata. Once
your errata are verified, your submission will be accepted and the errata will be uploaded to
our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to


https://www.packtpub.com/books/content/support and enter the name of the book in the search
field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At
Packt, we take the protection of our copyright and licenses very seriously. If you come across
any illegal copies of our works in any form on the Internet, please provide us with the
location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable
content.
Questions
If you have a problem with any aspect of this book, you can contact us at
[email protected], and we will do our best to address the problem.
Chapter 1. Introduction to FP, Reactive, and
Scala
In our first chapter, we will learn the basic concepts of Functional Programing (FP), reactive
programming, and the Scala language. These concepts are listed as follows:
Setting up a Scala development environment with Eclipse Scala IDE.
Basic constructs of the language like var, val, for, if, switch, and operator overload.
The difference between FP and object-oriented programming.
Principles of pure FP: immutability, no side effects, state discipline, composition, and
higher order functions.
Concepts of FP such as lambda, recursion, for comprehensions, partial functions,
Monads, currying, and functions.
Pattern Matcher, recursion, reflection, package objects, and concurrency.

Let's get going!


Functional programming
FP is not new at all. The very first implementation of FP is Lisp and is dated from the 1950s.
Currently, we are living in a post-functional programming era, where we have the strong
math principles and ideas from the 50s mixed with the most modern and beautiful piece of
engineering, also know as the Java Virtual Machine (JVM). Scala is a post-functional
programming language built on top of the JVM. Being on top of the JVM gives us a lot of
benefits such as the following:

Scala is a post-functional programming language built on top of the JVM. Being on top of the
JVM gives us a lot of benefits such as the following:
Reliability and performance: Java is used by 10 out of 10 top websites we have
currently, like Netflix, Apple, Uber, Twitter, Yahoo, eBay, Yelp, LinkedIn, Google,
Amazon, and many others. JVM is the best solution at scale and is battle-tested by these
web-scale companies.
Native JVM eco-system: Full access to all of the Java ecosystem including frameworks,
libraries, servers, and tools.
Operations leverage: Your operation team can run Scala in the same way they run Java.
Legacy code leverage: Scala allows you to easily integrate Scala code with Java code.
This feature is great because it enables Java legacy system integration inside the box.
Java interoperability: A code written in Scala can be accessed in Java.

Scala was created in 2001 at EPFL by Martin Odersky. Scala is a strong static-typed language,
and was inspired by another functional language called Haskell. Scala addresses several
criticisms of the Java language, and delivers a better developer experience through less code
and more concise programs, without losing performance.

Scala and Java share the same infrastructure as the JVM, but in terms of design, Scala is a
different language in comparison with Java. Java is an imperative object-oriented language
and Scala is a post-functional, multiparadigm programing language. FP works with different
principles than object-oriented programing (OOP). OOP got very popular and well
established in enterprise thanks to languages like Java, C#, Ruby, and Python. However,
languages like Scala, Clojure, F#, and Swift are gaining a huge momentum, and FP has grown
a lot in the last 10 years. Most of the new languages are pure functional, post-functional, or
hybrid (like Java 8). In this book, you will see Scala code compared with Java code so you
can see by yourself how Scala is way more compact, objective, and direct than Java and
imperative OOP languages.

FP started at academia and spread to the world; FP is everywhere. Big Data and Stream
processing solutions like Hadoop and Spark (built on top of Scala and Akka) are built on top
of FP ideas and principles. FP spread to UI with RxJavaScript - you can even find FP in a
database with Datomic (Clojure). Languages like Clojure and Scala made FP more practical
and attractive to enterprise and professional developers. In this book, we will be exploring
both principles and practical aspects of the Scala language.
Principles of functional programming
FP is a way of thinking, a specific style of constructing and building programs. Having an FP
language helps a lot in terms of syntax, but at the end of the day, it's all about ideas and
developer mindset. FP favors disciplined state management and immutability in a declarative
programming way rather than the imperative programming mostly used by OOP languages
such as Java, Python, and Ruby.

FP has roots in math back to Lambda calculus - a formal system developed in the 1930s.
Lambda calculus is a mathematical abstraction and not a programming language, but it is easy
to see its concepts in programming languages nowadays.

Imperative programming uses statements to change the program state. In other words, this
means you give commands to the program to perform actions. This way of thinking describes
a sequence of steps on how the program needs to operate. What you need to keep in mind is
the kind of style focus on how FP works in a different way, focusing on what the program
should accomplish without telling the program how to do it. When you are coding in FP, you
tend to use fewer variables, for loops, and IFS, and write more functions and make function
composition.

The following are the CORE principles of FP:


Immutability
Disciplined state
Pure functions and no side effects/disciplined states
First class functions and high order functions
Type systems
Referential transparency

Let's understand these principles in detail.


Immutability
The concept of immutability is the CORE of FP, and it means that once you assign a value to
something, that value won't change. This is very important, because it eliminates side effects
(anything outside of the local function scope), for instance, changing other variables outside
the function. Immutability makes it easier to read code, because you know the function that
you are using is a pure function. Since your function has a disciplined state and does not
change other variables outside of the function, you don't need to look at the code outside the
function definition. This sounds like you're not working with state at all, so how would it be
possible to write professional applications this way? Well, you will change state but in a very
disciplined way. You will create another instance or another pointer to that instance, but you
won't change that variable's value. Having immutability is the key to having better, faster, and
more correct programs, because you don't need to use locks and your code is parallel by
nature.
Disciplined state
Shared mutable state is evil, because it is much harder to scale and to run it concurrently.
What is shared mutable state? A simple way to see it is as a global variable that all your
functions have access to. Why is this bad? First of all, because it is hard to keep this state
correct since there are many functions that have direct access to this state. Second, if you are
performing refactoring, this kind of code is often the hardest to refactor as well. It's also hard
to read this code. This is because you can never trust the local method, since your local
method is just one part of the program. And with mutable state, you need to look up for all
the functions that use that variable, in order to understand the logic. It's hard to debug for the
very same reason. When you are coding with FP principles in mind, you avoid, as much as
possible, having a shared mutable state. Of course you can have state, but you should keep it
local, which means inside your function. This is the state discipline: you use state, but in a
very disciplined way. This is simple, but it could be hard especially if you are a professional
developer, because this aspect is now usual to see in enterprise languages such as Java, .NET,
Ruby, and Python.
Pure functions and no side effects
Pure functions are the ones with no side effects. Side effects are bad, because they are
unpredictable and make your software hard to test. Let's say you have a method that receives
no parameters and returns nothing--this is one of the worst things we could have, because
how do you test it? How can you reuse this code? This is not what we call a pure function.
What are the possible side effects? Database call, global variables, IO call, and so on. This
makes sense, but you cannot have a program with just pure functions, because it won't be
practical.
First-class functions and higher-order functions
First-class means that the language treats functions as first-class citizens. In other words, it
means having language support to pass functions as arguments to other functions and to
return values as functions. First-class function also implies that the language allows you to
store functions as variables or any other data structure.

Higher-order functions are related to First-class functions, but they are not the same thing.
Higher-order functions often means language support for partial functional application and
Currying. Higher-order functions are a mathematical concept where functions operate with
other functions.

Partial functions are when you can fix a value (argument) to a particular function, which you
may or may not change later on. This is great for function composition.

Currying is a technique to transform a function with multiple parameters in a sequence of


functions with each function having a single argument. Scala language does not force
currying, however, languages like ML and Haskell almost always use this kind of technique.
Type systems
Type system is all about the compiler. The idea is simple: you create a type system, and by
doing so, you leverage the compiler to avoid all kinds of mistakes and errors. This is because
the compiler helps in making sure that you only have the right types as arguments, turn
statements, function composition, and so on. The compiler will not allow you do make any
basic mistakes. Scala and Haskell are examples of languages that are Strong-type. Meanwhile,
Common Lisp, Scheme, and Clojure are dynamic languages that may accept wrong values
during compilation time. One of the biggest benefits of the strong type system is that you have
to write fewer tests, because the compiler will take care of several issues for you. For
instance, if you have a function that receives a string, it could be dangerous, because you can
pass pretty much anything in a string. However, if you have a function that receives a type
called salesman, then you don't write a validation to check if it is a salesman. All this may
sound silly, but in a real application, this saves lots of lines of code and makes you program
better. Another great benefit of strong typing is that you have better documentation, as your
code becomes your documentation, and it's way more clear what you can or can't do.
Referential transparency
Referential transparency is a concept which works close with pure functions and immutability
since your program has fewer assignment statements, and often when you have it, you tend to
never change that value. This is great because you eliminate side effects with this technique.
During program execution, any variable can be replaced since there are no side effects, and
the program becomes referentially transparent. Scala language makes this concept very clear
the moment you declare a variable.
Installing Java 8 and Scala 2.11
Scala requires JVM to work, so we need get the JDK 8 before installing Scala. Go to the
Oracle website, and download and install JDK 8 from
http://www.oracle.com/technetwork/pt/java/javase/downloads/index.html.

Once you've downloaded Java, we need to add Java to the PATH variable; otherwise, you can
use the terminal. We do this as follows:
$ cd ~/
$ wget --no-cookies --no-check-certificate --header "Cookie:
gpw_e24=https%3A%2F%2Fptop.only.wip.la%3A443%2Fhttp%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-
cookie" "
http://download.oracle.com/otn-pub/java/jdk/8u77-b03/jdk-8u77-linux-
i586.tar.gz"
$ tar -xzvf $ jdk-8u77-linux-x64.tar.gz
$ rm -f jdk-8u77-linux-x64.tar.gz

The next step is to create the environment variable called JAVA_HOME, and to put the Java 8
binaries in the PATH variable. In Linux, we need to edit the ~/.bashrc file, and export the
variables we need, like in the following:
export JAVA_HOME=~/jdk1.8.0_77
export PATH=$PATH:$JAVA_HOME/bin

Save the file, and then on the same terminal we need to source the file via $ source
~/.bashrc

Now we can test our Java 8 installation. Just type in $ java -version. You should see
something like the following:
$ java -version
java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) Server VM (build 25.77-b03, mixed mode)

Let's get started. We will be using the latest Scala version 2.11.8. However, the code inside this
book should work with any Scala 2.11.x version. First of all, let's download Scala from
http://www.scala-lang.org/.

Scala works on Windows, Mac, and Linux. For this book, I will show how to use Scala on
Ubuntu Linux(Debian-based). Open your browser and go to http://www.scala-
lang.org/download/.

Download scala 2.11.8: it will be a TGZ file. Extract it and add it to your path; otherwise,
you can use the terminal. Do this as follows:
$ cd ~/
$ wget http://downloads.lightbend.com/scala/2.11.8/scala-2.11.8.tgz
$ tar -xzvf scala-2.11.8.tgz
$ rm -rf scala-2.11.8.tgz

The next step is to create the environment variable called SCALA_HOME, and to put the Scala
binaries in the PATH variable. In Linux, we need to edit the ~/.bashrc file and export the
variables we need, like in the following:
export SCALA_HOME=~/scala-2.11.8/
export PATH=$PATH:$SCALA_HOME/bin

Save the file, and then, on the same terminal, we need to source the file via $ source
~/.bashrc.

Now we can test our Scala installation. Just type in $ scala -version. You should see
something like the following:
$ scala -version
Scala code runner version 2.11.8 -- Copyright 2002-2016, LAMP/EPFL

You have successfully installed Java 8 and Scala 2.11. Now we are ready to start learning the
FP principles in Scala. For this, we will be using the Scala REPL in the beginning. Scala REPL
is bundled with the default Scala installation, and you just need to type $ scala in your
terminal as follows:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala>
Scala REPL

Congratulations! You have installed Java 8 and Scala 2.11 successfully.


Read Eval Print and Loop - REPL
Read Eval Print and Loop (REPL) is also know as a language shell. Many other languages
have shells, like Lisp, Python, and Ruby for instance. The REPL is a simple environment to
experiment the language in. It's possible to write very complex programs using REPL, but this
is not the REPL goal. Using REPL does not invalidate the usage of an IDE like Eclipse or
IntelliJ IDEA. REPL is ideal for testing simple commands and programs without having to
spend much time configuring projects like you do with an IDE. The Scala REPL allows you to
create a variable, functions, classes, and complex functions as well. There is a history of
every command you perform; there is some level of autocomplete too. As a REPL user, you
can print variable values and call functions.
Scala Hello World using the REPL
Let's get started. Go ahead, open your terminal, and type $ scala in order to open the Scala
REPL. Once the REPL is open, you can just type "Hello World". By doing this, you perform
two operations: eval and print. The Scala REPL will create a variable called res0, and store
your String there. Then it will print the content of the res0 variable.
Scala REPL Hello World program
We will see how to create Hello World program in Scala REPL as follows:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> "Hello World"
res0: String = Hello World
scala>

Scala is a hybrid language, which means it is object-oriented and functional as well. You can
create classes and objects in Scala. Next we will create a complete Hello World application
using classes.
Scala object-oriented HelloWorld program
We will see how to create object-oriented HelloWorld program in Scala REPL as follows:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> object HelloWorld {
| def main(args:Array[String]) = println("Hello World")
| }
defined object HelloWorld
scala> HelloWorld.main(null)
Hello World
scala>

The first thing you need to realize is that we use the word object instead of class. The Scala
language has different constructs compared to Java. Object is a singleton in Scala. It's the
same as coding the singleton pattern in Java.

Next we see the word def that is used in Scala to create functions. In the preceding program,
we create the main function similar to the way we do it in Java, and we call the built-in
function println in order to print the String Hello World. Scala imports some Java objects
and packages by default. Coding in Scala does not require you to type, for instance,
System.out.println("Hello World"), but you can if you want. Let's take a look at it in the
following code:
$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_77).
Type in expressions for evaluation. Or try :help.
scala> System.out.println("Hello World")
Hello World
scala>

We can and we will do better. Scala has some abstractions for a console application, so we can
write this code with a lesser number of lines of code. To accomplish this goal, we need to
extend the Scala class App. When we extend from App, we perform inheritance and we don't
need to define the main function. We can just put all the code in the body of the class, which is
very convenient and makes the code clean and simple to read.
Random documents with unrelated
content Scribd suggests to you:
pertinent to record two things that have come to my notice since.
One is that in rereading Faye’s “Origine du Monde,” I came upon a
passage in which it appears that M. Blandet had actually consulted
Faye about his hypothesis, and that Faye had shown him its
impossibility on much the same grounds as those above referred to;
which, however, did not deter M. Blandet from giving it to the world
nor De Lapparent from god-fathering the conception.
Faye, meanwhile, developed his theory of the origin of the world,
and by it explained the greater heat and lesser light of paleologic
times compared with our own, thus: The Earth evolved before the
Sun. In paleologic times the Sun was still of great extent,—an
ungathered-up residue of nebula that had not yet fallen together
enough to concentrate, not a contracting mass from which the
planets had been detached,—and was in consequence but feebly
luminous and of little heating effect; so that there were no seasons
on Earth and no climatic zones. The Earth itself supplied the heat
felt uniformly over its whole surface.
This differs from my conception, as the reader will see presently,
in one vital point—as to why the Earth was not heated by the Sun.
In the first place Faye’s sun has no raison d’être; and in the second
no visible means of existence. If its matter were not already within
the orbit of the Earth at the time, there seems no reason why it
should ever get there; and if there, why it should have been so loath
to condense. We cannot admit, I think, any such juvenility in the Sun
at the time the Earth was already so far advanced as geology shows
it to have been in paleologic times. For the Earth had already cooled
below the boiling-point of water.
Tree fern.

To understand the problem from the Earth’s point of view, let us


review the facts with which geology presents us. The flora of
paleologic times, as we see both at their advent in the Devonian and
from their superb development in the Carboniferous era, consisted
wholly of forms whose descendants now seek the shade.[18] Tree
ferns, sigillaria, equisetæ, and other gloom-seeking plants composed
it. That some tree fern survivals to-day can bear the light does not
invalidate the racial tendency. We have plenty of instances in nature
of such adaptability to changed conditions. In fact, the dying out and
deterioration of most of the order shows that the conditions have
changed. And these plants, grown to the dimensions of trees,
inhabited equally the tropic, the temperate, and the frigid zones as
we know them now. Lastly, no annual rings of growth are to be
found on them.[19] In other words, they grew right on, day in, day
out. The climate, then, was as continuous as it was widespread.
On the other hand, astronomy and geology both assert that the
seas were warm.[20] From this it follows that a vastly greater
evaporation must have gone on then than now, and that a welkin of
cloud must thus inevitably have been formed.
Now put the two facts together, and you have the solution. The
climate was warm and equable over the whole globe because a thick
cloud envelope shut off the Sun’s heat, the heat being wholly
supplied from the steamy seas. At the same time, by the same
means the light was necessarily so tempered as to produce exactly
that half-light the ferns so dearly love. One and the same cause thus
answers the double riddle of greater warmth and less light in those
old days than is now the case.
And here comes in the second find I spoke of above, in the
person of some old trilobites who stepped in unexpectedly in
corroboration. It has long been known—though its full significance
seems to have escaped notice—that in 1872 M. Barrande made the
discovery that many species of trilobites of the Cambrian and lower
Silurian, the two lowest, and therefore the oldest, strata of paleozoic
times, and distant relative of our horseshoe crabs, were blind. What
is yet more significant, the most antediluvian were the least provided
with eyes. Thus in the primordial strata, one-fourth of the whole
number of species were eyeless, in the next above one-fifth, and in
the latest of all one two-hundredth only.[21] Furthermore, they
testify to the difficulty of seeing, in two distinct ways, some by
having no eyes and some colossal ones, strenuous individuals
increasing their equipment and the lazy letting it lapse. It seems
more than questionable to attribute this blindness to a deep-sea
habitat, as Suess does in describing them, for they lived in what
geologists agree were shallow seas on the site of Bohemia to-day.
Besides, trilobites never had abyssal proclivities; for they are found
preserved in littoral deposits, not in deep-sea silt. Muddy water may
have had some hand in this, but muddy water itself testifies to great
commotion above and torrential rains. So the light in those seas was
not what it became later, or would be now. Thus these trilobites
were antelucan members of their brotherhood, and this accuses a
lack of light in those earlier eras even greater than in Carboniferous
times, which is just where it ought to be found if the theory is true.
I trust this conception may prove acceptable to geologists, for it
seems imperative from the astronomic side that something of the
sort must have occurred. And it is just as well, if not better, to view
it thus in the light of the dawn of geologic history as to remain in the
dark about it altogether. Nescience is not science—whether
hyphenized or apart; for the whole object of science is to synthesize
and explain. Its body of learning is but the letter, coördination the
spirit, of its law. Nevertheless, the unpardonable impropriety of a
new idea, I am aware, is as reprehensible as the atrocious crime of
being a young man. Yet the world could not get on without both.
Time is a sure reformer and will render the most hardened case of
youth senile in the end. So even a new idea may grow respectable at
last. And it is really as well to make its acquaintance while it still has
vigor in it as to wait till it is old and may be embraced with impunity.
Boasted conservatism is troglodytic, and usually proves a self-
conferred euphuism for dull. For conservatism proceeds from
slowness of apprehension. It may be necessary for certain minds to
be in the rear of the procession, but it is of doubtful glory to find
distinction in the fact.
Thus the youth of a world, like the babyhood of an individual, is
passed screened from immediate contact from without. That this is
the only way that life can originate on a planet we cannot say, but
that it is away in which it does occur, our own Earth attests, and
that, moreover, it is the way with all planets of sufficient size, the
present aspect of the major planets shows. It may well be that with
celestial bodies as with earthly species, some swaddle their young,
others cast them forth to take their chance, and that those that most
protect them rear the higher progeny in the end. What glories in
evolution thus await the giant planets when they shall have
sufficiently cooled down, we can only dimly imagine. But we can
foresee enough to realize that we are not the sum of our solar
system’s possibilities, and by studying the skies read there a future
more wonderful than anything we know.
CHAPTER VII
A PLANET’S HISTORY
Sun-sustained Stage

Two stages have characterized the surface history of the Earth,—


stages which may be likened to the career of the chick within and
without the egg. In the first of them the Earth lay screened from
outside influence under a thick shell of cloud, indifferently exclusive
of the cold of space or of the heating beams of the Sun. Motherless,
the warmth of its own body brooded over it, keeping its heat from
dissipating too speedily into space, and so fostering the life that was
quickening upon its surface.
The second stage began when the egg-shell broke and the chick
lay exposed to the universe about it, to get its living no longer from
its little world within, but from the greater one without. One and the
same event ended the old life to make possible the new. So soon as
the cloud envelope was pierced, both the Earth’s own heat escaped
and the Sun’s rays were permitted to come in.
It is not surprising that under such changed conditions
development itself should have changed, too. In fact, the
transformation was marked. That its epochal character has failed to
impress itself generally on geologists, is perhaps because they look
too closely, missing the march of events in the events themselves,
and because, too, of the gradual nature of its processional change.
We can recall only De Lapparent as having particularly signalled it;
although not only in its cause, but for its effects, it should have
delimited two great geologic divisions of time.
Earth as seen from above—Photographed by Dr. Lowell
at an altitude of 5500 feet.

Astronomy and geology are each but part of one universal


history. The tale each has to tell must prove in keeping with that of
the other. If they seem at variance, it behooves us very carefully to
scan their respective stories to find the flaw where the apparent
incongruity slipped in. Each, too, fittingly supplements the other, and
especially must geology look to astronomy for its initial data, since
astronomy deals with the beginning of our own Earth.
That study of our Earth in its entirety falls properly within the
province of astronomy, is not only deducible from its relationship to
the other planets, but demonstrable from the cosmic causes that
have been at work upon it, and the inadequacy of anything but
cosmic laws to explain them. The ablest geologists to-day are
becoming aware of this,—we have one of them at the head of the
geology department of the Institute,—while from the curious
astronomy at second hand which gets printed in geologic text-books,
by eminent men at that, dating from some time before the flood,—of
modern ideas,—it seems high time that the connection should be
made clear.
For, after all, our Earth too is a heavenly body, in spite of man’s
doing his best to make it the reverse. It has some right to
astronomic regard, even if it is our own mother. At the same time it
is quite puerile to consider the universe as bounded by our terrestrial
backyard. If man took himself a thought less importantly, he might
perceive the humor of so circumscribed a view. Like children we play
at being alone in the universe, and then go them one better by
believing it too.
I shall, of course, not touch on any matters purely geologic, for
fear of committing the very excesses I deplore; mentioning only
such points as astronomy has information on, and which, by the
sidelights it throws, may help to illuminate the subject.
Thus it certainly is interesting and may to many be a new point
of view, that the changes introduced when paleologic times passed
into neologic ones were in their fundamental aspects essentially
astronomic; which shows how truly astronomic causes are woven
into the whole fabric of the Earth. For it was then only, terrestrially
speaking, that the year began. The orbital period had existed, of
course, from the time the Earth first made the circuit of the Sun. But
the year was more a succès d’estime on the Sun’s part than one of
popular appreciation. As the Sun could not be seen and worked no
striking effects upon the Earth, the annual round had no
recognizable parts, and one revolution lapsed into the next without
demarcation. Only with the clearing of the sky did the seasons come
in: to register time by stamping its record on the trees. Before that,
summer and winter, spring and autumn, were unknown.
Climate, too, made then its first appearance; climate, named
after the sunward obliquity of the Earth, and seeming at times to live
down to that characterization. Weather there had been before;
pejoratively speaking, nothing but weather. For the downpours in
paleologic times must have been exceeded in numbers only by their
force. One dull perpetual round of rain was the programme for the
day, with absolutely no hope of a happy clearance to-morrow. It was
the golden age only for weather prophets whose prognostications
could hardly go wrong. With climate, however, it was a very different
matter. With polyp corals building reefs almost to the pole (81° 50′),
[22] as far north nearly as man has yet by his utmost efforts
succeeded in getting, while their fellows were busy at the like
industry in the tropics, it is clear that latitude was laughed at and
climate even lacked a name.
Another astronomic feature, then for the first time disclosed, was
the full significance of the day and the revelation of its cause. While
the Earth brooded under perpetual cloud, there could have been but
imperfect recognition of day and night. Or perhaps we may put it
better by saying that the standard of both was greatly depressed,
dull days alternating with nights black as pitch. But the moment the
Sun was let in, all this changed, though not in a twinkling. The
change came on most gradually. We can see in our mind’s eye the
first openings in the great welkin permitting the Earth its initial
peeps of the world beyond, and how quickly and tantalously they
shut in again like a mid-storm morning which dreams of clearing
only to find how drowsy it still is. But eventually the clouds parted
afresh and farther, and the Earth began to open its eyes to the
universe without.
The cause of the clearing, of course, was the falling temperature
of the seas. Evaporation went on much less fast as the heat of the
water lessened. The whole round of aquatic travel from ocean to air,
and back to ocean again, proceeded at an ever slackening pace. And
here, if it so please geologists, may be found a reconciling of their
demands for time to the relative pittance astronomy has been willing
to dole them out, a paltry 50 or 100 millions of years, which like all
framers of budgets they have declared utterly insufficient. For in
early times the forces at work were greater, and by magnifying the
means you quicken the process and contract the Earth’s earlier eras
to reasonable limits.
Upon these various astronomic novelties, the Earth on thus
awakening looked for the first time. Such regard altered for good its
own internal relations. The wider outlook made impossible the life of
the narrower that preceded it. A totally changed set of animals and
plants arose, to whom the cosmos bore a different aspect. The Earth
ceased to be the self-centred spot it seemed before. As long ago as
this had the idea that our globe was the centre of the universe been
cosmically exploded. The Earth knew it if man did not.

Tracks of Sauropus primævus (× ½). I. Lea.—Dana,


“Manual of Geology.”

Its denizens responded. The organisms that already inhabited it


proceeded to change their character and crawl out upon the land.
For in Devonian times the Earth was the home of fishes. The land
was not considered a fit abode by anything but insects, and not
over-good by them. But it looked different when the Sun shone.
Some maritime dwellers felt tempted to explore, and proceeded in
the shape of amphibians to spy out the land. They have left very
readable accounts of their travels in footnotes by the way. As one
should always inspect the original documents, I will reproduce the
footnotes of one early explorer. It is one of the few copies we have,
as the type is worn out. But it tells a pretty full story as it stands.
The ripple-marks show that a sea beach it was which the discoverer
trod in his bold journey of a few feet from home and friends, and
the pits in the sandstone that it was raining at the time of his
excursion. No Columbus or Hakluyt could have left a record more
precise or more eminently trustworthy. The pilgrims found it so good
that their eventual collaterals, the great reptiles, actually took
possession of the land and held it for many centuries by right of
eminent domain. Yet throughout the time of these bold adventurers,
their skies were only clearing, as the pitting of the sandstone
eloquently states.
It was not till the chalk cliffs of Dover were being laid down that
we have evidence that seasons had fully developed, in the shape of
the first deciduous trees.[23] Cryptogams, cycads, and, finally,
conifers had in turn represented the highest attainments of
vegetation, and the last of these had already recognized the seasons
by a sort of half-hearted hibernation or annual moulting; deeming it
wise not to be off with the old leaves before they were on with the
new. But finally the most advanced among them decided
unreservedly to accept the winter and go to sleep till spring. The
larches and ginkgo trees are descendants of the leaders of this
coniferous progressive party.
At the same time color came in. We are not accustomed to
realize that nature drew the Earth in grays and greens, and touched
it up with color afterward. Only the tempered tints of the rocks and
the leaden blue of the sea, subdued by the disheartening welkin
overhead to a dull drab, enlivened their abode for the oldest
inhabitants. But with Tertiary times entered the brilliantly petalled
flowers. Beginning with yellow, these rose through a chromatic scale
of beauty from white through red to blue.[24] They decked
themselves thus gaudily because the Sun was there to see by, as
well as eyes to see. For without the Sun those unconscious
horticulturists, the insects, could not have exercised their pictorial
profession.
To the entering of the Sun upon the scene this wondrous
revolution was due; and once entered, it became the dominant
factor in the Earth’s organic life. We are in the habit of
apostrophizing the Sun as the source of all terrestrial existence. It is
true enough to-day, and has been so since man entered on the
scene. But it was not always thus. There was a time when the Sun
played no part in the world’s affairs.
As its heat is now all-important, it becomes an interesting matter
to determine the laws governing its amount. That summer is hotter
than winter we all know from experience, pleasurable or painful as
the case may be. This is due to the fact that the Sun is above the
horizon for a greater number of hours in summer and passes more
directly overhead. But not so many people are aware that on
midsummer day, so far as the Sun is concerned, the north pole
should be the hottest place on earth. That Arctic explorers, who
have got within speaking acquaintance of it, assure us it is not so,
shows that something besides the direct rays of the Sun is involved.
Indeed, we learn as much from the extensively advertised
thermometers of winter resorts which, judiciously placed, beguile the
stranger to sojourn where it is just too cold for comfort. The factor
in question is the blanketing character of our air. Now a blanket may
keep heat out as well as keep it in. Our air acts in both capacities. It
is by no means simply a storer of heat, as many people seem to
suppose; it is a heat-stopper as well. What it really is is a temporizer,
a buffer to ease the shocks of sudden change like those comfortable,
phlegmatic souls who reduce all emotion to a level. For the heating
power of the Sun, even at the Earth’s distance away, is much greater
than appears. Knowledge of this we owe most to Langley, and then
to Very, who continued his results to yet a finer determination, the
best we have to-day. In consequence we have learnt that the
amount of heat we should receive from the Sun, could we get above
our air,—the solar constant, as it is called,—would be over three
times what it is on the average in our latitude at the surface, and is
rising still, so to speak. For as man has gone higher he has found his
inferences rising too, and the limit would seem to be not yet. We see
then that the air to which we thought ourselves so much indebted,
actually begins its kindly offices by shutting off two-thirds of what
was coming to us. As it plays, however, something of the same trick
to what tries to escape, we are really somewhat beholden to it after
all.
But not so much as has been thought. We used to be told that
the Moon’s temperature even at midday hardly rose above freezing,
but Very has found it about 350° F., which even the most chilly of
souls might find warm. By the late afternoon, however, he would
need his overcoat, and no end of blankets subsequently, for during
the long lunar night of fourteen days the temperature must fall
appallingly low, to -300° F. or less.
As the determination of temperature is a vital one, not only to
any organic existence, but even to inorganic conditions upon a
planet, it behooves us to look carefully into the question of the
effective heat received from the Sun. Until recently the only criterion
in the case was assumed to be distance from the illuminating source,
about as efficient a mode of computation as estimating a Russian
army by its official roll. For as we saw in our own case, not all that
ought to ever gets to the front, to say nothing of what is lost there.
Yet on this worse than guesswork astronomic text-books still assert
as a fact that the temperature of other bodies—the Moon and Mars,
for example—must be excessively low.
Let us now examine into this most interesting problem. It is
intricate, of course, but I think you will find it more comprehensible
than you imagine. Indeed, I shall be to blame if you do not. For if
one knows his subject, he can always explain it, in untechnical
language, technical terms being merely a sort of shorthand for the
profession. The physical processes involved can be made clear
without difficulty, although their quantitative evaluation is less
forthrightly demonstrable. Let me, then, give you an epitome of my
investigation of the subject.
Adventures of a heat ray.

Consider a ray of light falling on a surface from the Sun. A part of


it is reflected; that is, is instantly thrown off again. By this part the
body shines and makes its show in the world, but gets no good
itself. Another part is absorbed; this alone goes to heat the body.
Now if the visible rays were all that emanated from the Sun, it would
be strictly true, and a pretty paradox for believers in the efficacy of
distance, that what heated the planet was precisely what seemed
not to do so. Unfortunately there are also invisible rays, and these,
too, are in part reflected and in part absorbed, and their ratio is
different from that of the visible ones. To appreciate them, Langley
invented the bolometer, in which heat falling on a strip of metal
produces a current of electricity registered by a galvanometer. By
thus recording the heat received at different parts of the spectrum
and at different heights in our atmosphere, he was able to find how
much the air cut off. Very has since determined this still more
accurately. By thus determining the depletion in the invisible part of
the spectrum joined to what astronomy tells us of the loss in the
visible part, we have a value for the whole amount. By knowing,
then, the immediate brightness of a planet and approximately the
amount of atmosphere it owns, we are enabled to judge how much
heat it actually receives. This proves to be, in the case of Mars, more
than twice as much as distance alone would lead us to infer.
The second question is how much of this it retains. The
temperature of a body at any moment is the balance struck between
what it receives and what it radiates. If it gets rid of a great deal of
its income, it will clearly be less hot than if it is miserly retentive. To
find how much it radiates we may take the difference in temperature
between sunset and sunrise, since during this interval the Earth
receives no heat from the Sun. In the same way the efficacy of
different atmospheric blankets may be judged. Thus the Earth parts
with nine centigrade degrees’ worth of its store on clear nights, and
only four degrees’ worth on cloudy ones, before morning. This is at
sea-level. By going up a high mountain we get another set of
depletions, and from this a relative scale for different atmospheric
blankets. This is the principle, and we only have to fill out the
skeleton of theory with appropriate numbers to find how warm the
body is.
In doing so, we light on some interesting facts. Thus clouds
reflect 72 per cent of the visible rays, letting through only 28 per
cent of them. We feel chilly when a cloud passes over the Sun. On
the other hand, slate reflects only 18 per cent of the visible rays,
absorbing all the rest. This is why slate gets so much hotter in the
Sun than chalk, and why men wear white in the tropics. White,
indeed, is the best color to clothe one’s self in the year around,
except for the cold effect it has on the imagination, for it keeps one’s
own heat in as well as keeping the Sun’s out. The modest, self-
obliterating, white winter habit of the polar hares not only enables
them to keep still and escape notice, but keeps them warm while
they wait.
Astronomically, the effect is equally striking. Mars, for example,
owing to being cloudless and of a duller hue, turns out to have a
computed mean temperature nearly equal to the Earth’s,—a
theoretic deduction which the aspect of the planet most obligingly
corroborates. It thus enjoys a comparatively genial old age.
For what is specially instructive in planetary economy is that, on
the whole, clear skies add more by what they let in than they
subtract by what they let out. If the Earth had no clouds at all, its
mean temperature would be higher than it is to-day. Thus as a
planet ages a beneficent compensation is brought about, the Sun’s
heat increasing as its own gives out. Not that the foreign
importation, however slight the duty levied on it by the air, ever fully
makes up for the loss of the domestic article, but it tempers the
refrigeration which inevitably occurs.
The subject of refrigeration leads us to one of the most puzzling
and vexed problems of geology: how to account for the great Ice
Age of which the manifest sign manuals both in Europe and in
America have so intrigued man since he began to read the riddle of
the rocks. Upon this, also, planetology throws some light.
If I needed an apology to the geologists for seeming again to
trespass on their particular domain, I might refer to the astrocomico
expositions put forward to account for the great Ice Age.
We can all remember Croll’s “Climate and Time,” a book which
can hardly be overpraised for its title and which had things worth
reading inside, too. It had in consequence no inconsiderable vogue
at one time. It undertook to account for glacial epochs on
astronomic principles. It called in such grand cosmic conditions and
dealt in such imposing periods of time that it fired fancy and almost
compelled capitulation by the mere marshalling of its figurative
array. Secular change in the eccentricity of the Earth’s orbit,
combined with progression in the orbital place of the winter’s
solstice, was supposed to have induced physical changes of climate
which accentuated the snowfall in the northern hemisphere and so
caused extensive and permanent glaciation there. In other words,
long, cold winters followed by short, hot summers in one
hemisphere were credited with accumulating a perpetual snow
sheet, such as short, warm winters and long, cold summers could
not effect.

Mars.
NORTH POLAR CAP. SOUTH POLAR CAP.
At maximum full extent of white At maximum white
At minimum inner circle At minimum nothing
Now it so happens that these astronomic conditions affecting the
Earth several thousand years ago, are in process of action on one of
our nearest planetary neighbors at the present time. The orbit of
Mars is such that its present eccentricity is greater than what the
Earth ever can have had, and the winter solstice of the planet’s
southern hemisphere falls within 23° of its aphelion point. We have
then the conditions for glaciation if these are the astronomic ones
supposed, and we should expect a southern polar cap, larger at its
maximum and still more so, relatively, at its minimum, than in the
opposite hemisphere. Let us now look at the facts, for we have now
a knowledge of the Martian polar caps exceeding in some respects
what we know of our own. The accompanying diagrams exhibit the
state of things at a glance, the maximum and minimum of each cap
being represented in a single picture and the two being placed side
by side. It will be observed that the southern cap outdoes its
antipodal counterpart at its maximum, showing that the longer,
colder winter has its effect in snow or hoar-frost deposition. But, on
the other hand, instead of excelling it at its minimum, which it
should do to produce permanent glaciation, it so far falls short of its
fellow that during the last opposition at which it could be well
observed, it disappeared entirely. The short, hot summer, then, far
exceeded in melting capacity that of the longer but colder one.
Let us now suppose the precipitation to be increased, the winters
and summers remaining both in length and temperature what they
were before. The amount of snow which a summer of given length
and warmth can dispose of is, roughly speaking, a definite quantity.
For it depends to a great extent only on its amount of heat. The
summer precipitation may be taken as offsetting itself in the two
hemispheres alike. If, then, the snowfall in the winter be for any
reason increased daily in both, a time will come when the deposition
due the longer winter of the one will exceed what its summer can
melt relatively to the other, and a permanent glaciation result in the
hemisphere so circumstanced. Increased precipitation, then, not
eccentricity of orbit, is the real cause of an Ice Age. And this
astronomic deduction we owe not to theoretic conclusions, for which
we lack the necessary quantitative data, but wholly to study of our
neighbor in space. Had any one informed our geologic colleagues
that they must look to the sky for definite information about the
cause of an Ice Age, they would probably have been surprised.
With this Martian information, received some years ago, it is
pleasing now to see that Earthly knowledge is gradually catching up.
For that increased precipitation could account for it, the evidence of
pluvial eras in the equatorial regions, contemporaneous with glacial
periods, indicates. But another and probably the chief factor involved
was not a generally increased precipitation, potent as that would be,
but an increased snow deposit due to temporary elevation of the
ground.

Glacial map of Eurasia—after James Geikie.


Map showing the glaciated area of North America—
the arrows indicating the direction of ice movement—
Chamberlin and Salisbury.
For it now appears that there was no glacial epoch. Our early
ideas inculcated by text-books at school received a rude shock when
it appeared that the glacial epoch was not, as we had been led to
believe, a polar phenomenon at all, but a local affair which on the
face of it had nothing to do with the pole. For investigation has
disclosed that instead of emanating from the pole southward, it
proceeded from certain centres, descending thence in all directions,
north as much as south. Thus there was a centre in Norway in 65°
N. lat. and another in Scotland in 56° N. In North America there
were three—the Labradorian in latitude 54° N., the Kerwatin to the
northwest of Hudson’s Bay in latitude 62° N., and the Cordilleran
along the Pacific coast in latitude 58° N. On the other hand,
northern Siberia, the coldest region in the world, was not glaciated.
That the ice flowed off these centres proves them to have been
higher than the sides. But we have further evidence of their then
great height from the fact that dead littoral shells have been
dredged from 1333 fathoms in the North Atlantic, and the
prolongation under water of the fiords of Norway and of land valleys
in North America witness to the same subsidence since.
But evidence refuses to stop here. The Alps were then more
glaciated than they are now. So was Kilimanjaro and Ruwenzori on
the equator; and finally at the same time more ice and snow existed
round about the south pole than is the case to-day. Now this is really
going too far even for the most ardent believers in the force of
eccentricity. For if the astronomic causes postulated were true, they
must have produced just the opposite action at the antipodes, to say
nothing of the crux of being equally effective at the equator. The
theory lies down like the ass between two burdens. Whichever load
it chooses to saddle, it must perforce abandon the other.
So it turns out that the Ice Age was not an Ice Age at all but an
untoward elevation of certain spots, and is to be relegated to the
same limbo of exaggeration of a local incident into a world-wide
cataclysm as the deluge. That some geologists will still cling to their
former belief I doubt not; for as the philosophic old lady remarked:
“There always have been two factions on every subject. Just as
there are the suffragists and anti-suffragists now, so there were
slaveholders and the anti-slavery people in my time; and even in the
days of the deluge, there were the diluvians who were in favor of a
flood and the antediluvians who were opposed to it.” A tale which
has a peculiarly scientific moral, as in science anti and ante seem
often interchangeable terms.
When I began the course of lectures that resulted in this volume,
I labored under the apprehension that an account of cosmic physics
might prove dull. It soon threatened to prove too startling. I
therefore hasten to reassure the timid by saying that we are
outgrowing ice ages and probably deluges. Elevations of the Earth’s
crust are likely to be less and less pronounced in the future, and
meanwhile such as exist are being slowly worn down. Secondly, the
Sun is sure to continue of much the same efficiency for many æons
to come. And lastly, the essential ingredient of both prodigies, water,
is daily becoming more scarce. To this latter point we now turn, and
perhaps when it is explained to him the reader may think that he
has been rescued from one fate only to fall into the hands of
another.
Geology is necessarily limited in its scope to what has happened;
planetology is not so circumscribed in its domain. It may indulge in
prognostication of the future, and find countenance for its
conclusions in the physiognomy of other worlds. Thus one of the
things which it foresees is the relative drying up of our abode. To
those whose studies have never led them off this earth, the fact that
the oceans are slowly evaporating into space may seem as incredible
as would, to one marooned on a desert island, the march of
mankind in the meantime. We live on an island in space, but can see
something of the islands about us, and our conception of what is
coming to our limited habitat can be judged most surely by what we
note has happened to others more advanced than ourselves. Just as
we look at Jupiter to perceive some likeness of what we once were,
the real image of which has travelled by this time far into the depths
of space beyond possibility of recall, so must we look to the Moon or
Mars if we desire to see some faint adumbration of the pass to
which we are likely to come. For from their lack of size they should
have preceded us on the road we are bound to travel. Now, both
these worlds to-day are water-lacking, in whole or part; the Moon
practically absolutely so, Mars so far as any oceans or seas are
concerned. We should do wisely then to take note. But we have
more definite information than simply their present presentments.
For both bear upon their faces marks of having held seas once upon
a time. They were once, then, more as we are now. We cannot of
course be sure, as we are unable to get near enough to scan their
surfaces for signs of erosive action. But so far as we can make out,
past seas best explain their appearance.

The Moon—Photographed at the Lowell Observatory.

So sealike, indeed, was their look that the first astronomers to


note them took them unhesitatingly for water expanses. Thus the
moment the telescope brought the Moon near enough for map
making of it we find the dark patches at once designated as seas.
The Sea of Serenity, the Sea of Showers, the Bay of Rainbows,
speak still of what once was supposed to be the nature of the dark,
smooth, lunar surfaces they name. Suggestively, indeed, in an opera
glass do they seem to lap the land. The Lake of Dreams fore-
shadowed what was eventually to be thought of them. With
increasing optical approach the substance evaporated, but the form
remained. It was speedily evident that there was no water there; yet
the semblance of its repository still lurked in those shadows and
suggests itself to one scanning their surfaces to-day. If they be not
old sea bottoms, they singularly mimic the reality in their smooth,
sloping floors and their long, curving lines of beach. Their strange
uniformity shows that something protected them from volcanic fury
while the rest of the lunar face was being corrugated. This
preservative points to some superincumbent pressure which can
have been no other than water. Lava-flows on such a scale seem
inadmissible. What these surfaces show and what they do not show
alike hint them sea bottoms once upon a time. In the strange chalk-
like hue of the lunar landscape they look like plaster of Paris death-
masks of the former seas.
A like history fell to the lot of the surface features of Mars. There
too, as soon as the telescope revealed them and their permanency
of place, the dark patches upon the planet’s face were forthrightly
taken for seas, and were so called: the Sea of the Sirens and the
Great Red Sea. Such they long continued to be deemed. The seas of
Mars held water in theory centuries after the idea of the lunar had
vanished into air. At last, ruthless science pricked the pretty bubble
analogy had pictured. Being so much farther off than the Moon, it
was much later that their true character came out. Come out it has,
though, within the last few years. Lines—some of the so called
canals—have been detected crossing the seas, lines persistent in
place. This has effectually disposed of any water in them. But here
again something of semblance is left behind. They are still the
darkest portions of the planet, and their tint changes in places with
the progress of the planet’s year. That their color is that of
vegetation, and that its change obeys the seasons, stamp it for
vegetation in fact. Thus these regions must be more humid than the
rest of Mars. They must, therefore, be lower. That they are thus
lower and possess a modicum of water to-day marks them out for
the spots where seas would be, were there any seas to be. As we
know of a vera causa which has for ages been tending to deplete
them, extrapolation from what is now going on returns them the
water they have lost and rehabilitates their ancient aquatic character.
To the far-sight of inference, seas they again become in the morning
of the ages long ago when Mars itself was young.
Nor is this the end of the evidence. When we compare
quantitatively the areas occupied by the quondam seas on Mars and
on the Moon, we find reason to increase our confidence in our
deduction. For the smaller body, the Moon, should have had less
water relatively, at the time when the seas there were laid down,
than the larger, Mars. Because from the moment its mass began to
collect, it was in process of parting with its gases, water-vapor
among the rest, and, as we shall see more in detail in the next
chapter, it had from the start less hold on them than Mars. Its
oceans, therefore, should have been less extensive than the Martian
ones. This is what the present lunar Mare seem to attest. They are
less extended than the dark areas of Mars. A fact which becomes the
more evident when we remember that the Moon has long turned the
same face to the Earth. Her shape, therefore, has been that of an
egg, with the apex pointing toward our world. Here the water would
chiefly collect. The greater part of the seas she ever had should be
on our side of her surface, the one she presents in perpetuity to our
gaze.
It is to the heavens that we must look for our surest information
on such a cosmic point, because of the long perspective other bodies
give us of our own career. Less conclusive, because dependent upon
less time, is any evidence our globe can offer. Yet even from it we
may learn something; if nothing else, that it does not contradict the
story of the sky. To it, therefore, we return, quickened in
apprehension by the sights we have elsewhere seen.
The first thing our sharpened sense causes us to note is the
spread of deserts even within historic times. Just as deserts show by
their latitudinal girdling of the Earth their direct dependence upon
the great system of planetary winds, as meteorologists recognizingly
call them, so a study of the fringes of these belts discloses their
encroachment upon formerly less arid lands. The southern borders
of the Mediterranean reveal this all the way from Carthage to
Palestine. The disappearance of their former peoples, leaving these
lands but scantily inhabited now, points to this; because other
regions, as India, which still retain a waterful climate, are as
populous as ever. Much of this is doubtless due to the overthrow of
dynasties and the ensuing lapse of irrigation, but query: Is it all? For
we have still more definite information in the drying up of the
streams which have left the aqueducts of Carthage without
continuation, as much to water on the one hand as to its drinkers on
the other. Men may leave because of lack of water, but water does
not leave because of dearth of men to drink.
Recent search around the Caspian by Huntington has disclosed
the like degeneration due to encroaching desertism there. Indeed, it
is no chance coincidence that just where all the great nations thrived
in the morning of the historic times should be precisely where
populous peoples no longer exist. For neither increasing cold nor
increasing heat is responsible for this, seeing that no general change
has occurred in either. Nor were they particularly exposed to
extermination by northern hordes of barbarians. Egypt as a world
power died a natural death, and Babylonia too; but the common
people died of thirst, indirect and unconscious and not wholly of
their own choosing. Prehistoric records make this conclusion doubly
sure, by lengthening the limit of our observation. Both extinct flora
and extinct fauna tell the same tale. In the neighborhood of Cairo
petrified forests attest that Egypt was not always a wiped slate,
while the unearthed animals of the Fayum bear witness to water
where no water is to-day.
Petrified bridge, third petrified forest, near
Adamana, Arizona—Photograph by Harvey.

Anywhere we wander along these girdling belts we find the same


story written for us to read. The great deserts of New Mexico and
Arizona show castellated structures far beyond the means of its
present Indian population to inhabit. Yet this retrenchment occurred
long before the white man came with his exterminating blight on
everything he touched. Nor have we reason to suppose that it arose
in consequence of invasion by other alien hordes. Individual
communities may thus indeed have perished as the preservation of
their domiciles intact leads us to infer, but all did not thus vanish
from off the Earth. Here again humanity died or moved away
because nature dried the sources of its supply. And here, as
elsewhere, we find prehistoric record in the rocks of a once more
smiling state of things, strengthening the testimony we deduce from
man. The forests, crowning now only the greater heights, are but
the shrinking residues of what once clothed the land. The well-
named Arid Zone is becoming more so every day.
If from the land evidence of drying up we turn to the marine, we
see the same shrinkage at work. It has even been discovered in a
lowering of the ocean bed, but as this may so easily be disputed, we
turn to one aspect of the situation which cannot so easily be
gainsaid,—the bodies of water that have been cut off. That the Dead
Sea, the Caspian, the Great Salt Lake, are slowly but surely giving
way to land, is patent. If the climate at least were not more arid
than before this could not occur; but more than this, if the ocean
were not on the whole shrinking, there would be no tendency to
leave such arms of itself behind to shrivel up. That the ocean basins
are deepening is possible, but we know of one depletion which is not
replaced—evaporation into space; and of another bound to come—
withdrawal into fissures when the earth shall cease to be too hot.
This gradual withdrawal of the water may seem an unpleasant
one to contemplate, but like most things it has its silver lining in the
hope it holds out that sometime there shall be no more sea. Those
of us who detest the constant going down to the sea in ships hardly
more than the occasional going down with them, can take a crumb
of comfort in the thought. Unfortunately it partakes of a somewhat
far-off realization in our distant descendants, coming a little too late
to be of material advantage to ourselves.
But let me not leave the reader wholly disconsolate. For another
thought we can take with us in closing our sketch of so much of the
Earth’s life as brings it well down to to-day,—the thought that it has
grown for us a steadily better place to contemplate from the earliest
eras to the present time. Indeed, with innate prescience we forbore
to appear till the prospect did prove pleasing. Finally, we may
palliate prognostication by considering that if its future seem a
thought less attractive, we, at least, shall not be there to see.
CHAPTER VIII
DEATH OF A WORLD

E
VERYTHING around us on this Earth we see is subject to one
inevitable cycle of birth, growth, decay. Nothing that begins but
comes at last to end. Not less is this true of the Earth as a
whole and of each of its sister planets. Though our own lives are too
brief even to mark the slow nearing to that eventual goal, the past
history of the Earth written in its rocks and the present aspects of
the several planets that circle similarly round the Sun alike assure us
of the course of aging as certainly as if time, with all it brings about,
passed in one long procession before our very eyes.
Death is a distressing thing to contemplate under any
circumstances, and not less so to a philosopher when that of a
whole world is concerned. To think that this fair globe with all it has
brought forth must lapse in time to nothingness; that the
generations of men shall cease to be, their very records obliterated,
is something to strike a chill into the heart of the most callous and
numb endeavor at its core. That æons must roll away before that
final day is to the mind of the far-seeing no consolation for the end.
Not only that we shall pass, but that everything to show we ever
were shall perish too, seems an extinction too overpowering for
words.
But vain regret avails not to change the universe’s course. What
is concerns us and what will be too. From facing it we cannot turn
away. We may alleviate its poignancy by the thought that our
interest is after all remote, affecting chiefly descendants we shall
never know, and commend to ourselves the altruistic example so
nobly set us by doctors of medicine who, on the demise of others at
which—and possibly to which—they have themselves assisted, show
a fortitude not easily surpassed, a fortitude extending even to their
bills. If they can act thus unshaken at sight of their contemporaries,
we should not fall behind them in heroism toward posterity.
Having in our last chapter run the gantlet of the geologists, we
are in some sort fortified to face death—in a world—in this. The
more so that we have some millenniums of respite before the
execution of the decree. By the death of a planet we may designate
that stage when all change on its surface, save disintegration,
ceases. For then all we know as life in its manifold manifestations is
at an end. To this it may come by many paths. For a planet, like a
man, is exposed to death from a variety of untoward events.
Of these the one least likely to occur is death by accident. This,
celestially speaking, is anything which may happen to the solar
system from without, and is of the nature of an unforeseen
catastrophe. Our Sun might, as we remarked, be run into. For so far
as we know at present the stars are moving among themselves
without any too careful regard for one another. The swarm may be
circling a central Sun as André states, but the individual stars behave
more like the random particles of a gas with licensed freedom to
collide; whereas we may liken the members of the solar system to
molecules in the solid state held to a centre from which they can
never greatly depart. Their motions thus afford a sense of security
lacking in the universe at large.
Such an accident, a collision actual or virtual with another sun,
would probably occur with some dark star; of which we sketched the
ultimate results in our first chapter. The immediate ones would be of
a most disastrous kind. For prefatory to the new birth would be the
dissolution to make such resurrection possible. Destruction might
come direct, or indirectly through the Sun. For though the Sun would
be the tramp’s objective point, we might inadvertently find ourselves
in the way. The choice would be purely academic; between being
powdered, or deorbited and burnt up.
So remote is this contingency that it need cause us no immediate
alarm, as I carefully pointed out. But so strong is the instinct of self-
preservation and so pleasurable the sensation of spreading appalling
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!

ebookgate.com

You might also like