SlideShare a Scribd company logo
Building Applications with Scala 1st Edition
Pacheco download
https://ebookgate.com/product/building-applications-with-
scala-1st-edition-pacheco/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats
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/
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/
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/
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/
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/
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/
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/
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/
Professional Scala 1st Edition Janek Bogucki
https://ebookgate.com/product/professional-scala-1st-edition-
janek-bogucki/
Building Applications with Scala 1st Edition Pacheco
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
Diego Pacheco
Copy Editor
Sonia Mathur
Reviewer
Yuanhang Wang
Project Coordinator
Suzanne Coutinho
Commissioning Editor
Kunal Parikh
Proofreader
Safis Editing
Acquisition Editor
Denim Pinto
Indexer
Tejal Daruwale Soni
Content Development Editor
Rohit Singh
Graphics
Jason Monteiro
Technical Editor
Jijo Maliyekal
Production Coordinator
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 service@packtpub.com 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 feedback@packtpub.com, 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 copyright@packtpub.com 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
questions@packtpub.com, 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=http%3A%2F%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.
Discovering Diverse Content Through
Random Scribd Documents
Building Applications with Scala 1st Edition Pacheco
E
ESTHER
1
Nine.
STHER’S hair falls in soft curls about her high-cheek-boned chalk-
white face. Esther’s hair would be beautiful if there were more
gloss to it. And if her face were not prematurely serious, one would
call it pretty. Her cheeks are too flat and dead for a girl of nine.
Esther looks like a little white child, starched, frilled, as she walks
slowly from her home towards her father’s grocery store. She is
about to turn in Broad from Maple Street. White and black men
loafing on the corner hold no interest for her. Then a strange thing
happens. A clean-muscled, magnificent, black-skinned Negro, whom
she had heard her father mention as King Barlo, suddenly drops to
his knees on a spot called the Spittoon. White men, unaware of him,
continue squirting tobacco juice in his direction. The saffron fluid
splashes on his face. His smooth black face begins to glisten and to
shine. Soon, people notice him, and gather round. His eyes are
rapturous upon the heavens. Lips and nostrils quiver. Barlo is in a
religious trance. Town folks know it. They are not startled. They are
not afraid. They gather round. Some beg boxes from the grocery
stores. From old McGregor’s notion shop. A coffin-case is pressed
into use. Folks line the curb-stones. Business men close shop. And
Banker Warply parks his car close by. Silently, all await the prophet’s
voice. The sheriff, a great florid fellow whose leggings never meet
around his bulging calves, swears in three deputies. “Wall, y cant
never tell what a nigger like King Barlo might be up t.” Soda bottles,
five fingers full of shine, are passed to those who want them. A
couple of stray dogs start a fight. Old Goodlow’s cow comes flopping
up the street. Barlo, still as an Indian fakir, has not moved. The town
bell strikes six. The sun slips in behind a heavy mass of horizon
cloud. The crowd is hushed and expectant. Barlo’s under jaw
relaxes, and his lips begin to move.
“Jesus has been awhisperin strange words deep down, O way
down deep, deep in my ears.”
Hums of awe and of excitement.
“He called me to His side an said, 'Git down on your knees beside
me, son, Ise gwine t whisper in your ears.’”
An old sister cries, “Ah, Lord.”
“'Ise agwine t whisper in your ears,’ he said, an I replied, 'Thy will
be done on earth as it is in heaven.’”
“Ah, Lord. Amen. Amen.”
“An Lord Jesus whispered strange good words deep down, O way
down deep, deep in my ears. An He said, 'Tell em till you feel your
throat on fire.’ I saw a vision. I saw a man arise, an he was big an
black an powerful—”
Some one yells, “Preach it, preacher, preach it!”
“—but his head was caught up in th clouds. An while he was
agazin at th heavens, heart filled up with th Lord, some little white-
ant biddies came an tied his feet to chains. They led him t th coast,
they led him t th sea, they led him across th ocean an they didnt set
him free. The old coast didnt miss him, an th new coast wasnt free,
he left the old-coast brothers, t give birth t you an me. O Lord, great
God Almighty, t give birth t you an me.”
Barlo pauses. Old gray mothers are in tears. Fragments of
melodies are being hummed. White folks are touched and curiously
awed. Off to themselves, white and black preachers confer as to
how best to rid themselves of the vagrant, usurping fellow. Barlo
looks as though he is struggling to continue. People are hushed. One
can hear weevils work. Dusk is falling rapidly, and the customary
store lights fail to throw their feeble glow across the gray dust and
flagging of the Georgia town. Barlo rises to his full height. He is
immense. To the people he assumes the outlines of his visioned
African. In a mighty voice he bellows:
“Brothers an sisters, turn your faces t th sweet face of the Lord,
an fill your hearts with glory. Open your eyes an see th dawnin of th
mornin light. Open your ears—”
Years afterwards Esther was told that at that very moment a
great, heavy, rumbling voice actually was heard. That hosts of
angels and of demons paraded up and down the streets all night.
That King Barlo rode out of town astride a pitch-black bull that had a
glowing gold ring in its nose. And that old Limp Underwood, who
hated niggers, woke up next morning to find that he held a black
man in his arms. This much is certain: an inspired Negress, of wide
reputation for being sanctified, drew a portrait of a black madonna
on the court-house wall. And King Barlo left town. He left his image
indelibly upon the mind of Esther. He became the starting point of
the only living patterns that her mind was to know.
2
Sixteen.
Esther begins to dream. The low evening sun sets the windows of
McGregor’s notion shop aflame. Esther makes believe that they
really are aflame. The town fire department rushes madly down the
road. It ruthlessly shoves black and white idlers to one side. It
whoops. It clangs. It rescues from the second-story window a
dimpled infant which she claims for her own. How had she come by
it? She thinks of it immaculately. It is a sin to think of it
immaculately. She must dream no more. She must repent her sin.
Another dream comes. There is no fire department. There are no
heroic men. The fire starts. The loafers on the corner form a circle,
chew their tobacco faster, and squirt juice just as fast as they can
chew. Gallons on top of gallons they squirt upon the flames. The air
reeks with the stench of scorched tobacco juice. Women, fat chunky
Negro women, lean scrawny white women, pull their skirts up above
their heads and display the most ludicrous underclothes. The women
scoot in all directions from the danger zone. She alone is left to take
the baby in her arms. But what a baby! Black, singed, woolly,
tobacco-juice baby—ugly as sin. Once held to her breast, miraculous
thing: its breath is sweet and its lips can nibble. She loves it
frantically. Her joy in it changes the town folks’ jeers to harmless
jealousy, and she is left alone.
Twenty-two.
Esther’s schooling is over. She works behind the counter of her
father’s grocery store. “To keep the money in the family,” so he said.
She is learning to make distinctions between the business and the
social worlds. “Good business comes from remembering that the
white folks dont divide the niggers, Esther. Be just as black as any
man who has a silver dollar.” Esther listlessly forgets that she is near
white, and that her father is the richest colored man in town. Black
folk who drift in to buy lard and snuff and flour of her, call her a
sweet-natured, accommodating girl. She learns their names. She
forgets them. She thinks about men. “I dont appeal to them. I
wonder why.” She recalls an affair she had with a little fair boy while
still in school. It had ended in her shame when he as much as told
her that for sweetness he preferred a lollipop. She remembers the
salesman from the North who wanted to take her to the movies that
first night he was in town. She refused, of course. And he never
came back, having found out who she was. She thinks of Barlo.
Barlo’s image gives her a slightly stale thrill. She spices it by telling
herself his glories. Black. Magnetically so. Best cotton picker in the
county, in the state, in the whole world for that matter. Best man
with his fists, best man with dice, with a razor. Promoter of church
benefits. Of colored fairs. Vagrant preacher. Lover of all the women
for miles and miles around. Esther decides that she loves him. And
with a vague sense of life slipping by, she resolves that she will tell
him so, whatever people say, the next time he comes to town. After
the making of this resolution which becomes a sort of wedding cake
for her to tuck beneath her pillow and go to sleep upon, she sees
nothing of Barlo for five years. Her hair thins. It looks like the dull
silk on puny corn ears. Her face pales until it is the color of the gray
dust that dances with dead cotton leaves...
3
Esther is twenty-seven.
Esther sells lard and snuff and flour to vague black faces that drift
in her store to ask for them. Her eyes hardly see the people to
whom she gives change. Her body is lean and beaten. She rests
listlessly against the counter, too weary to sit down. From the street
some one shouts, “King Barlo has come back to town.” He passes
her window, driving a large new car. Cut-out open. He veers to the
curb, and steps out. Barlo has made money on cotton during the
war. He is as rich as anyone. Esther suddenly is animate. She goes
to her door. She sees him at a distance, the center of a group of
credulous men. She hears the deep-bass rumble of his talk. The sun
swings low. McGregor’s windows are aflame again. Pale flame. A
sharply dressed white girl passes by. For a moment Esther wishes
that she might be like her. Not white; she has no need for being
that. But sharp, sporty, with get-up about her. Barlo is connected
with that wish. She mustnt wish. Wishes only make you restless.
Emptiness is a thing that grows by being moved. “I’ll not think. Not
wish. Just set my mind against it.” Then the thought comes to her
that those purposeless, easy-going men will possess him, if she
doesnt. Purpose is not dead in her, now that she comes to think of
it. That loose women will have their arms around him at Nat Bowle’s
place to-night. As if her veins are full of fired sun-bleached southern
shanties, a swift heat sweeps them. Dead dreams, and a forgotten
resolution are carried upward by the flames. Pale flames. “They
shant have him. Oh, they shall not. Not if it kills me they shant have
him.” Jerky, aflutter, she closes the store and starts home. Folks
lazing on store window-sills wonder what on earth can be the matter
with Jim Crane’s gal, as she passes them. “Come to remember, she
always was a little off, a little crazy, I reckon.” Esther seeks her own
room, and locks the door. Her mind is a pink mesh-bag filled with
baby toes.
Using the noise of the town clock striking twelve to cover the
creaks of her departure, Esther slips into the quiet road. The town,
her parents, most everyone is sound asleep. This fact is a stable
thing that comforts her. After sundown a chill wind came up from the
west. It is still blowing, but to her it is a steady, settled thing like the
cold. She wants her mind to be like that. Solid, contained, and blank
as a sheet of darkened ice. She will not permit herself to notice the
peculiar phosphorescent glitter of the sweet-gum leaves. Their
movement would excite her. Exciting too, the recession of the dull
familiar homes she knows so well. She doesnt know them at all. She
closes her eyes, and holds them tightly. Wont do. Her being aware
that they are closed recalls her purpose. She does not want to think
of it. She opens them. She turns now into the deserted business
street. The corrugated iron canopies and mule- and horse-gnawed
hitching posts bring her a strange composure. Ghosts of the
commonplaces of her daily life take stride with her and become her
companions. And the echoes of her heels upon the flagging are
rhythmically monotonous and soothing. Crossing the street at the
corner of McGregor’s notion shop, she thinks that the windows are a
dull flame. Only a fancy. She walks faster. Then runs. A turn into a
side street brings her abruptly to Nat Bowle’s place. The house is
squat and dark. It is always dark. Barlo is within. Quietly she opens
the outside door and steps in. She passes through a small room.
Pauses before a flight of stairs down which people’s voices, muffled,
come. The air is heavy with fresh tobacco smoke. It makes her sick.
She wants to turn back. She goes up the steps. As if she were
mounting to some great height, her head spins. She is violently
dizzy. Blackness rushes to her eyes. And then she finds that she is in
a large room. Barlo is before her.
“Well, I’m sholy damned—skuse me, but what, what brought you
here, lil milk-white gal?”
“You.” Her voice sounds like a frightened child’s that calls
homeward from some point miles away.
“Me?”
“Yes, you Barlo.”
“This aint th place fer y. This aint th place fer y.”
“I know. I know. But I’ve come for you.”
“For me for what?”
She manages to look deep and straight into his eyes. He is slow at
understanding. Guffaws and giggles break out from all around the
room. A coarse woman’s voice remarks, “So thats how th dictie
niggers does it.” Laughs. “Mus give em credit fo their gall.”
Esther doesnt hear. Barlo does. His faculties are jogged. She sees
a smile, ugly and repulsive to her, working upward through thick
licker fumes. Barlo seems hideous. The thought comes suddenly,
that conception with a drunken man must be a mighty sin. She
draws away, frozen. Like a somnambulist she wheels around and
walks stiffly to the stairs. Down them. Jeers and hoots pelter bluntly
upon her back. She steps out. There is no air, no street, and the
town has completely disappeared.
Building Applications with Scala 1st Edition Pacheco
CONVERSION
African Guardian of Souls,
Drunk with rum,
Feasting on a strange cassava,
Yielding to new words and a weak palabra
Of a white-faced sardonic god—
Grins, cries
Amen,
Shouts hosanna.
Building Applications with Scala 1st Edition Pacheco
PORTRAIT IN GEORGIA
Hair—braided chestnut, coiled like a lyncher’s rope,
Eyes—fagots,
Lips—old scars, or the first red blisters,
Breath—the last sweet scent of cane,
And her slim body, white as the ash of black flesh after flame.
Building Applications with Scala 1st Edition Pacheco
U
BLOOD-BURNING MOON
1
P from the skeleton stone walls, up from the rotting floor boards
and the solid hand-hewn beams of oak of the pre-war cotton
factory, dusk came. Up from the dusk the full moon came. Glowing
like a fired pine-knot, it illumined the great door and soft showered
the Negro shanties aligned along the single street of factory town.
The full moon in the great door was an omen. Negro women
improvised songs against its spell.
Louisa sang as she came over the crest of the hill from the white
folks’ kitchen. Her skin was the color of oak leaves on young trees in
fall. Her breasts, firm and up-pointed like ripe acorns. And her
singing had the low murmur of winds in fig trees. Bob Stone,
younger son of the people she worked for, loved her. By the way the
world reckons things, he had won her. By measure of that warm
glow which came into her mind at thought of him, he had won her.
Tom Burwell, whom the whole town called Big Boy, also loved her.
But working in the fields all day, and far away from her, gave him no
chance to show it. Though often enough of evenings he had tried to.
Somehow, he never got along. Strong as he was with hands upon
the ax or plow, he found it difficult to hold her. Or so he thought. But
the fact was that he held her to factory town more firmly than he
thought for. His black balanced, and pulled against, the white of
Stone, when she thought of them. And her mind was vaguely upon
them as she came over the crest of the hill, coming from the white
folks’ kitchen. As she sang softly at the evil face of the full moon.
A strange stir was in her. Indolently, she tried to fix upon Bob or
Tom as the cause of it. To meet Bob in the canebrake, as she was
going to do an hour or so later, was nothing new. And Tom’s
proposal which she felt on its way to her could be indefinitely put off.
Separately, there was no unusual significance to either one. But for
some reason, they jumbled when her eyes gazed vacantly at the
rising moon. And from the jumble came the stir that was strangely
within her. Her lips trembled. The slow rhythm of her song grew
agitant and restless. Rusty black and tan spotted hounds, lying in
the dark corners of porches or prowling around back yards, put their
noses in the air and caught its tremor. They began plaintively to yelp
and howl. Chickens woke up and cackled. Intermittently, all over the
countryside dogs barked and roosters crowed as if heralding a weird
dawn or some ungodly awakening. The women sang lustily. Their
songs were cotton-wads to stop their ears. Louisa came down into
factory town and sank wearily upon the step before her home. The
moon was rising towards a thick cloud-bank which soon would hide
it.
Red nigger moon. Sinner!
Blood-burning moon. Sinner!
Come out that fact’ry door.
2
Up from the deep dusk of a cleared spot on the edge of the forest
a mellow glow arose and spread fan-wise into the low-hanging
heavens. And all around the air was heavy with the scent of boiling
cane. A large pile of cane-stalks lay like ribboned shadows upon the
ground. A mule, harnessed to a pole, trudged lazily round and round
the pivot of the grinder. Beneath a swaying oil lamp, a Negro
alternately whipped out at the mule, and fed cane-stalks to the
grinder. A fat boy waddled pails of fresh ground juice between the
grinder and the boiling stove. Steam came from the copper boiling
pan. The scent of cane came from the copper pan and drenched the
forest and the hill that sloped to factory town, beneath its fragrance.
It drenched the men in circle seated around the stove. Some of
them chewed at the white pulp of stalks, but there was no need for
them to, if all they wanted was to taste the cane. One tasted it in
factory town. And from factory town one could see the soft haze
thrown by the glowing stove upon the low-hanging heavens.
Old David Georgia stirred the thickening syrup with a long ladle,
and ever so often drew it off. Old David Georgia tended his stove
and told tales about the white folks, about moonshining and cotton
picking, and about sweet nigger gals, to the men who sat there
about his stove to listen to him. Tom Burwell chewed cane-stalk and
laughed with the others till someone mentioned Louisa. Till some
one said something about Louisa and Bob Stone, about the silk
stockings she must have gotten from him. Blood ran up Tom’s neck
hotter than the glow that flooded from the stove. He sprang up.
Glared at the men and said, “She’s my gal.” Will Manning laughed.
Tom strode over to him. Yanked him up and knocked him to the
ground. Several of Manning’s friends got up to fight for him. Tom
whipped out a long knife and would have cut them to shreds if they
hadnt ducked into the woods. Tom had had enough. He nodded to
Old David Georgia and swung down the path to factory town. Just
then, the dogs started barking and the roosters began to crow. Tom
felt funny. Away from the fight, away from the stove, chill got to
him. He shivered. He shuddered when he saw the full moon rising
towards the cloud-bank. He who didnt give a godam for the fears of
old women. He forced his mind to fasten on Louisa. Bob Stone.
Better not be. He turned into the street and saw Louisa sitting
before her home. He went towards her, ambling, touched the brim of
a marvelously shaped, spotted, felt hat, said he wanted to say
something to her, and then found that he didnt know what he had to
say, or if he did, that he couldnt say it. He shoved his big fists in his
overalls, grinned, and started to move off.
“Youall want me, Tom?”
“Thats what us wants, sho, Louisa.”
“Well, here I am—”
“An here I is, but that aint ahelpin none, all th same.”
“You wanted to say something?..”
“I did that, sho. But words is like th spots on dice: no matter how
y fumbles em, there’s times when they jes wont come. I dunno why.
Seems like th love I feels fo yo done stole m tongue. I got it now.
Whee! Louisa, honey, I oughtnt tell y, I feel I oughtnt cause yo is
young an goes t church an I has had other gals, but Louisa I sho do
love y. Lil gal, Ise watched y from them first days when youall sat
right here befo yo door befo th well an sang sometimes in a way
that like t broke m heart. Ise carried y with me into th fields, day
after day, an after that, an I sho can plow when yo is there, an I can
pick cotton. Yassur! Come near beatin Barlo yesterday. I sho did.
Yassur! An next year if ole Stone’ll trust me, I’ll have a farm. My
own. My bales will buy yo what y gets from white folks now. Silk
stockings an purple dresses—course I dont believe what some folks
been whisperin as t how y gets them things now. White folks always
did do for niggers what they likes. An they jes cant help alikin yo,
Louisa. Bob Stone likes y. Course he does. But not th way folks is
awhisperin. Does he, hon?”
“I dont know what you mean, Tom.”
“Course y dont. Ise already cut two niggers. Had t hon, t tell em
so. Niggers always tryin t make somethin out a nothin. An then
besides, white folks aint up t them tricks so much nowadays. Godam
better not be. Leastawise not with yo. Cause I wouldnt stand f it.
Nassur.”
“What would you do, Tom?”
“Cut him jes like I cut a nigger.”
“No, Tom—”
“I said I would an there aint no mo to it. But that aint th talk f
now. Sing, honey Louisa, an while I’m listenin t y I’ll be makin love.”
Tom took her hand in his. Against the tough thickness of his own,
hers felt soft and small. His huge body slipped down to the step
beside her. The full moon sank upward into the deep purple of the
cloud-bank. An old woman brought a lighted lamp and hung it on
the common well whose bulky shadow squatted in the middle of the
road, opposite Tom and Louisa. The old woman lifted the well-lid,
took hold the chain, and began drawing up the heavy bucket. As she
did so, she sang. Figures shifted, restless-like, between lamp and
window in the front rooms of the shanties. Shadows of the figures
fought each other on the gray dust of the road. Figures raised the
windows and joined the old woman in song. Louisa and Tom, the
whole street, singing:
Red nigger moon. Sinner!
Blood-burning moon. Sinner!
Come out that fact’ry door.
3
Bob Stone sauntered from his veranda out into the gloom of fir
trees and magnolias. The clear white of his skin paled, and the flush
of his cheeks turned purple. As if to balance this outer change, his
mind became consciously a white man’s. He passed the house with
its huge open hearth which, in the days of slavery, was the
plantation cookery. He saw Louisa bent over that hearth. He went in
as a master should and took her. Direct, honest, bold. None of this
sneaking that he had to go through now. The contrast was repulsive
to him. His family had lost ground. Hell no, his family still owned the
niggers, practically. Damned if they did, or he wouldnt have to duck
around so. What would they think if they knew? His mother? His
sister? He shouldnt mention them, shouldnt think of them in this
connection. There in the dusk he blushed at doing so. Fellows about
town were all right, but how about his friends up North? He could
see them incredible, repulsed. They didnt know. The thought first
made him laugh. Then, with their eyes still upon him, he began to
feel embarrassed. He felt the need of explaining things to them.
Explain hell. They wouldnt understand, and moreover, who ever
heard of a Southerner getting on his knees to any Yankee, or
anyone. No sir. He was going to see Louisa to-night, and love her.
She was lovely—in her way. Nigger way. What way was that?
Damned if he knew. Must know. He’d known her long enough to
know. Was there something about niggers that you couldnt know?
Listening to them at church didnt tell you anything. Looking at them
didnt tell you anything. Talking to them didnt tell you anything—
unless it was gossip, unless they wanted to talk. Of course, about
farming, and licker, and craps—but those werent nigger. Nigger was
something more. How much more? Something to be afraid of, more?
Hell no. Who ever heard of being afraid of a nigger? Tom Burwell.
Cartwell had told him that Tom went with Louisa after she reached
home. No sir. No nigger had ever been with his girl. He’d like to see
one try. Some position for him to be in. Him, Bob Stone, of the old
Stone family, in a scrap with a nigger over a nigger girl. In the good
old days... Ha! Those were the days. His family had lost ground. Not
so much, though. Enough for him to have to cut through old
Lemon’s canefield by way of the woods, that he might meet her. She
was worth it. Beautiful nigger gal. Why nigger? Why not, just gal?
No, it was because she was nigger that he went to her. Sweet... The
scent of boiling cane came to him. Then he saw the rich glow of the
stove. He heard the voices of the men circled around it. He was
about to skirt the clearing when he heard his own name mentioned.
He stopped. Quivering. Leaning against a tree, he listened.
“Bad nigger. Yassur, he sho is one bad nigger when he gets
started.”
“Tom Burwell’s been on th gang three times fo cuttin men.”
“What y think he’s agwine t do t Bob Stone?”
“Dunno yet. He aint found out. When he does— Baby!”
“Aint no tellin.”
“Young Stone aint no quitter an I ken tell y that. Blood of th old
uns in his veins.”
“Thats right. He’ll scrap, sho.”
“Be gettin too hot f niggers round this away.”
“Shut up, nigger. Y dont know what y talkin bout.”
Bob Stone’s ears burned as though he had been holding them
over the stove. Sizzling heat welled up within him. His feet felt as if
they rested on red-hot coals. They stung him to quick movement. He
circled the fringe of the glowing. Not a twig cracked beneath his
feet. He reached the path that led to factory town. Plunged furiously
down it. Halfway along, a blindness within him veered him aside. He
crashed into the bordering canebrake. Cane leaves cut his face and
lips. He tasted blood. He threw himself down and dug his fingers in
the ground. The earth was cool. Cane-roots took the fever from his
hands. After a long while, or so it seemed to him, the thought came
to him that it must be time to see Louisa. He got to his feet and
walked calmly to their meeting place. No Louisa. Tom Burwell had
her. Veins in his forehead bulged and distended. Saliva moistened
the dried blood on his lips. He bit down on his lips. He tasted blood.
Not his own blood; Tom Burwell’s blood. Bob drove through the cane
and out again upon the road. A hound swung down the path before
him towards factory town. Bob couldnt see it. The dog loped aside
to let him pass. Bob’s blind rushing made him stumble over it. He fell
with a thud that dazed him. The hound yelped. Answering yelps
came from all over the countryside. Chickens cackled. Roosters
crowed, heralding the bloodshot eyes of southern awakening.
Singers in the town were silenced. They shut their windows down.
Palpitant between the rooster crows, a chill hush settled upon the
huddled forms of Tom and Louisa. A figure rushed from the shadow
and stood before them. Tom popped to his feet.
“Whats y want?”
“I’m Bob Stone.”
“Yassur—an I’m Tom Burwell. Whats y want?”
Bob lunged at him. Tom side-stepped, caught him by the shoulder,
and flung him to the ground. Straddled him.
“Let me up.”
“Yassur—but watch yo doins, Bob Stone.”
A few dark figures, drawn by the sound of scuffle stood about
them. Bob sprang to his feet.
“Fight like a man, Tom Burwell, an I’ll lick y.”
Again he lunged. Tom side-stepped and flung him to the ground.
Straddled him.
“Get off me, you godam nigger you.”
“Yo sho has started somethin now. Get up.”
Tom yanked him up and began hammering at him. Each blow
sounded as if it smashed into a precious, irreplaceable soft
something. Beneath them, Bob staggered back. He reached in his
pocket and whipped out a knife.
“Thats my game, sho.”
Blue flash, a steel blade slashed across Bob Stone’s throat. He had
a sweetish sick feeling. Blood began to flow. Then he felt a sharp
twitch of pain. He let his knife drop. He slapped one hand against his
neck. He pressed the other on top of his head as if to hold it down.
He groaned. He turned, and staggered towards the crest of the hill
in the direction of white town. Negroes who had seen the fight slunk
into their homes and blew the lamps out. Louisa, dazed, hysterical,
refused to go indoors. She slipped, crumbled, her body loosely
propped against the woodwork of the well. Tom Burwell leaned
against it. He seemed rooted there.
Bob reached Broad Street. White men rushed up to him. He
collapsed in their arms.
“Tom Burwell....”
White men like ants upon a forage rushed about. Except for the
taut hum of their moving, all was silent. Shotguns, revolvers, rope,
kerosene, torches. Two high-powered cars with glaring search-lights.
They came together. The taut hum rose to a low roar. Then nothing
could be heard but the flop of their feet in the thick dust of the road.
The moving body of their silence preceded them over the crest of
the hill into factory town. It flattened the Negroes beneath it. It
rolled to the wall of the factory, where it stopped. Tom knew that
they were coming. He couldnt move. And then he saw the search-
lights of the two cars glaring down on him. A quick shock went
through him. He stiffened. He started to run. A yell went up from the
mob. Tom wheeled about and faced them. They poured down on
him. They swarmed. A large man with dead-white face and flabby
cheeks came to him and almost jabbed a gun-barrel through his
guts.
“Hands behind y, nigger.”
Tom’s wrist were bound. The big man shoved him to the well.
Burn him over it, and when the woodwork caved in, his body would
drop to the bottom. Two deaths for a godam nigger. Louisa was
driven back. The mob pushed in. Its pressure, its momentum was
too great. Drag him to the factory. Wood and stakes already there.
Tom moved in the direction indicated. But they had to drag him.
They reached the great door. Too many to get in there. The mob
divided and flowed around the walls to either side. The big man
shoved him through the door. The mob pressed in from the sides.
Taut humming. No words. A stake was sunk into the ground. Rotting
floor boards piled around it. Kerosene poured on the rotting floor
boards. Tom bound to the stake. His breast was bare. Nails scratches
let little lines of blood trickle down and mat into the hair. His face,
his eyes were set and stony. Except for irregular breathing, one
would have thought him already dead. Torches were flung onto the
pile. A great flare muffled in black smoke shot upward. The mob
yelled. The mob was silent. Now Tom could be seen within the
flames. Only his head, erect, lean, like a blackened stone. Stench of
burning flesh soaked the air. Tom’s eyes popped. His head settled
downward. The mob yelled. Its yell echoed against the skeleton
stone walls and sounded like a hundred yells. Like a hundred mobs
yelling. Its yell thudded against the thick front wall and fell back.
Ghost of a yell slipped through the flames and out the great door of
the factory. It fluttered like a dying thing down the single street of
factory town. Louisa, upon the step before her home, did not hear it,
but her eyes opened slowly. They saw the full moon glowing in the
great door. The full moon, an evil thing, an omen, soft showering the
homes of folks she knew. Where were they, these people? She’d
sing, and perhaps they’d come out and join her. Perhaps Tom
Burwell would come. At any rate, the full moon in the great door
was an omen which she must sing to:
Red nigger moon. Sinner!
Blood-burning moon. Sinner!
Come out that fact’ry door.
Building Applications with Scala 1st Edition Pacheco
S
SEVENTH STREET
Money burns the pocket, pocket hurts,
Bootleggers in silken shirts,
Ballooned, zooming Cadillacs,
Whizzing, whizzing down the street-car tracks.
EVENTH STREET is a bastard of Prohibition and the War. A crude-
boned, soft-skinned wedge of nigger life breathing its loafer air,
jazz songs and love, thrusting unconscious rhythms, black reddish
blood into the white and whitewashed wood of Washington. Stale
soggy wood of Washington. Wedges rust in soggy wood... Split it! In
two! Again! Shred it! .. the sun. Wedges are brilliant in the sun;
ribbons of wet wood dry and blow away. Black reddish blood.
Pouring for crude-boned soft-skinned life, who set you flowing?
Blood suckers of the War would spin in a frenzy of dizziness if they
drank your blood. Prohibition would put a stop to it. Who set you
flowing? White and whitewash disappear in blood. Who set you
flowing? Flowing down the smooth asphalt of Seventh Street, in
shanties, brick office buildings, theaters, drug stores, restaurants,
and cabarets? Eddying on the corners? Swirling like a blood-red
smoke up where the buzzards fly in heaven? God would not dare to
suck black red blood. A Nigger God! He would duck his head in
shame and call for the Judgment Day. Who set you flowing?
Money burns the pocket, pocket hurts,
Bootleggers in silken shirts,
Ballooned, zooming Cadillacs,
Whizzing, whizzing down the street-car tracks.
Building Applications with Scala 1st Edition Pacheco
R
RHOBERT
HOBERT wears a house, like a monstrous diver’s helmet, on his
head. His legs are banty-bowed and shaky because as a child he
had rickets. He is way down. Rods of the house like antennæ of a
dead thing, stuffed, prop up in the air. He is way down. He is
sinking. His house is a dead thing that weights him down. He is
sinking as a diver would sink in mud should the water be drawn off.
Life is a murky, wiggling, microscopic water that compresses him.
Compresses his helmet and would crush it the minute that he pulled
his head out. He has to keep it in. Life is water that is being drawn
off.
Brother, life is water that is being drawn off.
Brother, life is water that is being drawn off.
The dead house is stuffed. The stuffing is alive. It is sinful to draw
one’s head out of live stuffing in a dead house. The propped-up
antennæ would cave in and the stuffing be strewn .. shredded life-
pulp .. in the water. It is sinful to have one’s own head crushed.
Rhobert is an upright man whose legs are banty-bowed and shaky
because as a child he had rickets. The earth is round. Heaven is a
sphere that surrounds it. Sink where you will. God is a Red Cross
man with a dredge and a respiration-pump who’s waiting for you at
the opposite periphery. God built the house. He blew His breath into
its stuffing. It is good to die obeying Him who can do these things.
A futile something like the dead house wraps the live stuffing of
the question: how long before the water will be drawn off? Rhobert
does not care. Like most men who wear monstrous helmets, the
pressure it exerts is enough to convince him of its practical infinity.
And he cares not two straws as to whether or not he will ever see
his wife and children again. Many a time he’s seen them drown in his
dreams and has kicked about joyously in the mud for days after. One
thing about him goes straight to the heart. He has an Adam’s-apple
which strains sometimes as if he were painfully gulping great
globules of air .. air floating shredded life-pulp. It is a sad thing to
see a banty-bowed, shaky, ricket-legged man straining the raw
insides of his throat against smooth air. Holding furtive thoughts
about the glory of pulp-heads strewn in water... He is way down.
Down. Mud, coming to his banty knees, almost hides them. Soon
people will be looking at him and calling him a strong man. No doubt
he is for one who has had rickets. Lets give it to him. Lets call him
great when the water shall have been all drawn off. Lets build a
monument and set it in the ooze where he goes down. A monument
of hewn oak, carved in nigger-heads. Lets open our throats, brother,
and sing “Deep River” when he goes down.
Brother, Rhobert is sinking.
Lets open our throats, brother,
Lets sing Deep River when he goes down.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

PPT
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
PDF
Develop realtime web with Scala and Xitrum
PPT
Evolving IGN’s New APIs with Scala
PDF
Play framework
PDF
Play Framework and Activator
PPTX
Scala adoption by enterprises
PPTX
What is scala
PDF
Get Programming with Scala MEAP V05 Daniela Sfregola
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Develop realtime web with Scala and Xitrum
Evolving IGN’s New APIs with Scala
Play framework
Play Framework and Activator
Scala adoption by enterprises
What is scala
Get Programming with Scala MEAP V05 Daniela Sfregola

Similar to Building Applications with Scala 1st Edition Pacheco (20)

PDF
Your First Scala Web Application using Play 2.1
PDF
Short intro to scala and the play framework
PDF
Scala Applied Machine Learning 1st Edition Pascal Bugnion
PPTX
Introduction to Scala
PPT
Why scala - executive overview
PPTX
Scala in practice
PDF
Adobe Master Collection CC Crack 2025 FREE
PPTX
Evolving Scala, Scalar conference, Warsaw, March 2025
PDF
WTFAST Crack Latest Version FREE Downlaod 2025
PDF
uTorrent Pro Crack Latest Version free 2025
PDF
AOMEI Partition Assistant Crack 2025 FREE
PDF
K7 Total Security 16.0.1260 Crack + License Key Free
PPTX
Sviluppare applicazioni nell'era dei "Big Data" con Scala e Spark - Mario Car...
PDF
Lecture1
KEY
Java to Scala: Why & How
PPTX
Introduction to Scala language
PPTX
Alberto Paro - Hands on Scala.js
PPTX
Scala Italy 2015 - Hands On ScalaJS
PDF
Programming Scala 3rd Edition Dean Wampler Dean Wampler
KEY
The Why and How of Scala at Twitter
Your First Scala Web Application using Play 2.1
Short intro to scala and the play framework
Scala Applied Machine Learning 1st Edition Pascal Bugnion
Introduction to Scala
Why scala - executive overview
Scala in practice
Adobe Master Collection CC Crack 2025 FREE
Evolving Scala, Scalar conference, Warsaw, March 2025
WTFAST Crack Latest Version FREE Downlaod 2025
uTorrent Pro Crack Latest Version free 2025
AOMEI Partition Assistant Crack 2025 FREE
K7 Total Security 16.0.1260 Crack + License Key Free
Sviluppare applicazioni nell'era dei "Big Data" con Scala e Spark - Mario Car...
Lecture1
Java to Scala: Why & How
Introduction to Scala language
Alberto Paro - Hands on Scala.js
Scala Italy 2015 - Hands On ScalaJS
Programming Scala 3rd Edition Dean Wampler Dean Wampler
The Why and How of Scala at Twitter
Ad

Recently uploaded (20)

PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Complications of Minimal Access Surgery at WLH
PPTX
master seminar digital applications in india
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Basic Mud Logging Guide for educational purpose
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Institutional Correction lecture only . . .
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Lesson notes of climatology university.
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Microbial disease of the cardiovascular and lymphatic systems
Insiders guide to clinical Medicine.pdf
Final Presentation General Medicine 03-08-2024.pptx
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Anesthesia in Laparoscopic Surgery in India
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Complications of Minimal Access Surgery at WLH
master seminar digital applications in india
PPH.pptx obstetrics and gynecology in nursing
Basic Mud Logging Guide for educational purpose
Module 4: Burden of Disease Tutorial Slides S2 2025
Institutional Correction lecture only . . .
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Lesson notes of climatology university.
TR - Agricultural Crops Production NC III.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Ad

Building Applications with Scala 1st Edition Pacheco

  • 1. Building Applications with Scala 1st Edition Pacheco download https://ebookgate.com/product/building-applications-with- scala-1st-edition-pacheco/ Get Instant Ebook Downloads – Browse at https://ebookgate.com
  • 2. Get Your Digital Files Instantly: PDF, ePub, MOBI and More Quick Digital Downloads: PDF, ePub, MOBI and Other Formats 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/ 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/ 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/ 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/
  • 3. 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/ 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/ 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/ 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/ Professional Scala 1st Edition Janek Bogucki https://ebookgate.com/product/professional-scala-1st-edition- janek-bogucki/
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 14. 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
  • 15. Credits Author Diego Pacheco Copy Editor Sonia Mathur Reviewer Yuanhang Wang Project Coordinator Suzanne Coutinho Commissioning Editor Kunal Parikh Proofreader Safis Editing Acquisition Editor Denim Pinto Indexer Tejal Daruwale Soni Content Development Editor Rohit Singh Graphics Jason Monteiro Technical Editor Jijo Maliyekal Production Coordinator Melwyn Dsa
  • 16. 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/).
  • 17. 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!
  • 18. 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.
  • 19. 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 service@packtpub.com 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.
  • 20. 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
  • 21. 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.
  • 22. 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.
  • 23. 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
  • 24. 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.
  • 25. 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.
  • 26. 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 feedback@packtpub.com, 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.
  • 27. 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.
  • 28. 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!
  • 29. 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
  • 30. 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.
  • 31. 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 copyright@packtpub.com with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
  • 32. Questions If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.
  • 33. 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!
  • 34. 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
  • 35. both principles and practical aspects of the Scala language.
  • 36. 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.
  • 37. 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.
  • 38. 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.
  • 39. 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.
  • 40. 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.
  • 41. 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.
  • 42. 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.
  • 43. 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=http%3A%2F%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
  • 44. $ 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.
  • 45. 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.
  • 46. 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.
  • 47. 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.
  • 48. 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.
  • 49. Discovering Diverse Content Through Random Scribd Documents
  • 51. E ESTHER 1 Nine. STHER’S hair falls in soft curls about her high-cheek-boned chalk- white face. Esther’s hair would be beautiful if there were more gloss to it. And if her face were not prematurely serious, one would call it pretty. Her cheeks are too flat and dead for a girl of nine. Esther looks like a little white child, starched, frilled, as she walks slowly from her home towards her father’s grocery store. She is about to turn in Broad from Maple Street. White and black men loafing on the corner hold no interest for her. Then a strange thing happens. A clean-muscled, magnificent, black-skinned Negro, whom she had heard her father mention as King Barlo, suddenly drops to his knees on a spot called the Spittoon. White men, unaware of him, continue squirting tobacco juice in his direction. The saffron fluid splashes on his face. His smooth black face begins to glisten and to shine. Soon, people notice him, and gather round. His eyes are rapturous upon the heavens. Lips and nostrils quiver. Barlo is in a religious trance. Town folks know it. They are not startled. They are not afraid. They gather round. Some beg boxes from the grocery stores. From old McGregor’s notion shop. A coffin-case is pressed into use. Folks line the curb-stones. Business men close shop. And Banker Warply parks his car close by. Silently, all await the prophet’s voice. The sheriff, a great florid fellow whose leggings never meet around his bulging calves, swears in three deputies. “Wall, y cant never tell what a nigger like King Barlo might be up t.” Soda bottles, five fingers full of shine, are passed to those who want them. A couple of stray dogs start a fight. Old Goodlow’s cow comes flopping up the street. Barlo, still as an Indian fakir, has not moved. The town bell strikes six. The sun slips in behind a heavy mass of horizon
  • 52. cloud. The crowd is hushed and expectant. Barlo’s under jaw relaxes, and his lips begin to move. “Jesus has been awhisperin strange words deep down, O way down deep, deep in my ears.” Hums of awe and of excitement. “He called me to His side an said, 'Git down on your knees beside me, son, Ise gwine t whisper in your ears.’” An old sister cries, “Ah, Lord.” “'Ise agwine t whisper in your ears,’ he said, an I replied, 'Thy will be done on earth as it is in heaven.’” “Ah, Lord. Amen. Amen.” “An Lord Jesus whispered strange good words deep down, O way down deep, deep in my ears. An He said, 'Tell em till you feel your throat on fire.’ I saw a vision. I saw a man arise, an he was big an black an powerful—” Some one yells, “Preach it, preacher, preach it!” “—but his head was caught up in th clouds. An while he was agazin at th heavens, heart filled up with th Lord, some little white- ant biddies came an tied his feet to chains. They led him t th coast, they led him t th sea, they led him across th ocean an they didnt set him free. The old coast didnt miss him, an th new coast wasnt free, he left the old-coast brothers, t give birth t you an me. O Lord, great God Almighty, t give birth t you an me.” Barlo pauses. Old gray mothers are in tears. Fragments of melodies are being hummed. White folks are touched and curiously awed. Off to themselves, white and black preachers confer as to how best to rid themselves of the vagrant, usurping fellow. Barlo looks as though he is struggling to continue. People are hushed. One can hear weevils work. Dusk is falling rapidly, and the customary store lights fail to throw their feeble glow across the gray dust and flagging of the Georgia town. Barlo rises to his full height. He is
  • 53. immense. To the people he assumes the outlines of his visioned African. In a mighty voice he bellows: “Brothers an sisters, turn your faces t th sweet face of the Lord, an fill your hearts with glory. Open your eyes an see th dawnin of th mornin light. Open your ears—” Years afterwards Esther was told that at that very moment a great, heavy, rumbling voice actually was heard. That hosts of angels and of demons paraded up and down the streets all night. That King Barlo rode out of town astride a pitch-black bull that had a glowing gold ring in its nose. And that old Limp Underwood, who hated niggers, woke up next morning to find that he held a black man in his arms. This much is certain: an inspired Negress, of wide reputation for being sanctified, drew a portrait of a black madonna on the court-house wall. And King Barlo left town. He left his image indelibly upon the mind of Esther. He became the starting point of the only living patterns that her mind was to know. 2 Sixteen. Esther begins to dream. The low evening sun sets the windows of McGregor’s notion shop aflame. Esther makes believe that they really are aflame. The town fire department rushes madly down the road. It ruthlessly shoves black and white idlers to one side. It whoops. It clangs. It rescues from the second-story window a dimpled infant which she claims for her own. How had she come by it? She thinks of it immaculately. It is a sin to think of it immaculately. She must dream no more. She must repent her sin. Another dream comes. There is no fire department. There are no heroic men. The fire starts. The loafers on the corner form a circle, chew their tobacco faster, and squirt juice just as fast as they can chew. Gallons on top of gallons they squirt upon the flames. The air reeks with the stench of scorched tobacco juice. Women, fat chunky Negro women, lean scrawny white women, pull their skirts up above
  • 54. their heads and display the most ludicrous underclothes. The women scoot in all directions from the danger zone. She alone is left to take the baby in her arms. But what a baby! Black, singed, woolly, tobacco-juice baby—ugly as sin. Once held to her breast, miraculous thing: its breath is sweet and its lips can nibble. She loves it frantically. Her joy in it changes the town folks’ jeers to harmless jealousy, and she is left alone. Twenty-two. Esther’s schooling is over. She works behind the counter of her father’s grocery store. “To keep the money in the family,” so he said. She is learning to make distinctions between the business and the social worlds. “Good business comes from remembering that the white folks dont divide the niggers, Esther. Be just as black as any man who has a silver dollar.” Esther listlessly forgets that she is near white, and that her father is the richest colored man in town. Black folk who drift in to buy lard and snuff and flour of her, call her a sweet-natured, accommodating girl. She learns their names. She forgets them. She thinks about men. “I dont appeal to them. I wonder why.” She recalls an affair she had with a little fair boy while still in school. It had ended in her shame when he as much as told her that for sweetness he preferred a lollipop. She remembers the salesman from the North who wanted to take her to the movies that first night he was in town. She refused, of course. And he never came back, having found out who she was. She thinks of Barlo. Barlo’s image gives her a slightly stale thrill. She spices it by telling herself his glories. Black. Magnetically so. Best cotton picker in the county, in the state, in the whole world for that matter. Best man with his fists, best man with dice, with a razor. Promoter of church benefits. Of colored fairs. Vagrant preacher. Lover of all the women for miles and miles around. Esther decides that she loves him. And with a vague sense of life slipping by, she resolves that she will tell him so, whatever people say, the next time he comes to town. After the making of this resolution which becomes a sort of wedding cake for her to tuck beneath her pillow and go to sleep upon, she sees nothing of Barlo for five years. Her hair thins. It looks like the dull
  • 55. silk on puny corn ears. Her face pales until it is the color of the gray dust that dances with dead cotton leaves... 3 Esther is twenty-seven. Esther sells lard and snuff and flour to vague black faces that drift in her store to ask for them. Her eyes hardly see the people to whom she gives change. Her body is lean and beaten. She rests listlessly against the counter, too weary to sit down. From the street some one shouts, “King Barlo has come back to town.” He passes her window, driving a large new car. Cut-out open. He veers to the curb, and steps out. Barlo has made money on cotton during the war. He is as rich as anyone. Esther suddenly is animate. She goes to her door. She sees him at a distance, the center of a group of credulous men. She hears the deep-bass rumble of his talk. The sun swings low. McGregor’s windows are aflame again. Pale flame. A sharply dressed white girl passes by. For a moment Esther wishes that she might be like her. Not white; she has no need for being that. But sharp, sporty, with get-up about her. Barlo is connected with that wish. She mustnt wish. Wishes only make you restless. Emptiness is a thing that grows by being moved. “I’ll not think. Not wish. Just set my mind against it.” Then the thought comes to her that those purposeless, easy-going men will possess him, if she doesnt. Purpose is not dead in her, now that she comes to think of it. That loose women will have their arms around him at Nat Bowle’s place to-night. As if her veins are full of fired sun-bleached southern shanties, a swift heat sweeps them. Dead dreams, and a forgotten resolution are carried upward by the flames. Pale flames. “They shant have him. Oh, they shall not. Not if it kills me they shant have him.” Jerky, aflutter, she closes the store and starts home. Folks lazing on store window-sills wonder what on earth can be the matter with Jim Crane’s gal, as she passes them. “Come to remember, she always was a little off, a little crazy, I reckon.” Esther seeks her own
  • 56. room, and locks the door. Her mind is a pink mesh-bag filled with baby toes. Using the noise of the town clock striking twelve to cover the creaks of her departure, Esther slips into the quiet road. The town, her parents, most everyone is sound asleep. This fact is a stable thing that comforts her. After sundown a chill wind came up from the west. It is still blowing, but to her it is a steady, settled thing like the cold. She wants her mind to be like that. Solid, contained, and blank as a sheet of darkened ice. She will not permit herself to notice the peculiar phosphorescent glitter of the sweet-gum leaves. Their movement would excite her. Exciting too, the recession of the dull familiar homes she knows so well. She doesnt know them at all. She closes her eyes, and holds them tightly. Wont do. Her being aware that they are closed recalls her purpose. She does not want to think of it. She opens them. She turns now into the deserted business street. The corrugated iron canopies and mule- and horse-gnawed hitching posts bring her a strange composure. Ghosts of the commonplaces of her daily life take stride with her and become her companions. And the echoes of her heels upon the flagging are rhythmically monotonous and soothing. Crossing the street at the corner of McGregor’s notion shop, she thinks that the windows are a dull flame. Only a fancy. She walks faster. Then runs. A turn into a side street brings her abruptly to Nat Bowle’s place. The house is squat and dark. It is always dark. Barlo is within. Quietly she opens the outside door and steps in. She passes through a small room. Pauses before a flight of stairs down which people’s voices, muffled, come. The air is heavy with fresh tobacco smoke. It makes her sick. She wants to turn back. She goes up the steps. As if she were mounting to some great height, her head spins. She is violently dizzy. Blackness rushes to her eyes. And then she finds that she is in a large room. Barlo is before her. “Well, I’m sholy damned—skuse me, but what, what brought you here, lil milk-white gal?”
  • 57. “You.” Her voice sounds like a frightened child’s that calls homeward from some point miles away. “Me?” “Yes, you Barlo.” “This aint th place fer y. This aint th place fer y.” “I know. I know. But I’ve come for you.” “For me for what?” She manages to look deep and straight into his eyes. He is slow at understanding. Guffaws and giggles break out from all around the room. A coarse woman’s voice remarks, “So thats how th dictie niggers does it.” Laughs. “Mus give em credit fo their gall.” Esther doesnt hear. Barlo does. His faculties are jogged. She sees a smile, ugly and repulsive to her, working upward through thick licker fumes. Barlo seems hideous. The thought comes suddenly, that conception with a drunken man must be a mighty sin. She draws away, frozen. Like a somnambulist she wheels around and walks stiffly to the stairs. Down them. Jeers and hoots pelter bluntly upon her back. She steps out. There is no air, no street, and the town has completely disappeared.
  • 59. CONVERSION African Guardian of Souls, Drunk with rum, Feasting on a strange cassava, Yielding to new words and a weak palabra Of a white-faced sardonic god— Grins, cries Amen, Shouts hosanna.
  • 61. PORTRAIT IN GEORGIA Hair—braided chestnut, coiled like a lyncher’s rope, Eyes—fagots, Lips—old scars, or the first red blisters, Breath—the last sweet scent of cane, And her slim body, white as the ash of black flesh after flame.
  • 63. U BLOOD-BURNING MOON 1 P from the skeleton stone walls, up from the rotting floor boards and the solid hand-hewn beams of oak of the pre-war cotton factory, dusk came. Up from the dusk the full moon came. Glowing like a fired pine-knot, it illumined the great door and soft showered the Negro shanties aligned along the single street of factory town. The full moon in the great door was an omen. Negro women improvised songs against its spell. Louisa sang as she came over the crest of the hill from the white folks’ kitchen. Her skin was the color of oak leaves on young trees in fall. Her breasts, firm and up-pointed like ripe acorns. And her singing had the low murmur of winds in fig trees. Bob Stone, younger son of the people she worked for, loved her. By the way the world reckons things, he had won her. By measure of that warm glow which came into her mind at thought of him, he had won her. Tom Burwell, whom the whole town called Big Boy, also loved her. But working in the fields all day, and far away from her, gave him no chance to show it. Though often enough of evenings he had tried to. Somehow, he never got along. Strong as he was with hands upon the ax or plow, he found it difficult to hold her. Or so he thought. But the fact was that he held her to factory town more firmly than he thought for. His black balanced, and pulled against, the white of Stone, when she thought of them. And her mind was vaguely upon them as she came over the crest of the hill, coming from the white folks’ kitchen. As she sang softly at the evil face of the full moon. A strange stir was in her. Indolently, she tried to fix upon Bob or Tom as the cause of it. To meet Bob in the canebrake, as she was going to do an hour or so later, was nothing new. And Tom’s
  • 64. proposal which she felt on its way to her could be indefinitely put off. Separately, there was no unusual significance to either one. But for some reason, they jumbled when her eyes gazed vacantly at the rising moon. And from the jumble came the stir that was strangely within her. Her lips trembled. The slow rhythm of her song grew agitant and restless. Rusty black and tan spotted hounds, lying in the dark corners of porches or prowling around back yards, put their noses in the air and caught its tremor. They began plaintively to yelp and howl. Chickens woke up and cackled. Intermittently, all over the countryside dogs barked and roosters crowed as if heralding a weird dawn or some ungodly awakening. The women sang lustily. Their songs were cotton-wads to stop their ears. Louisa came down into factory town and sank wearily upon the step before her home. The moon was rising towards a thick cloud-bank which soon would hide it. Red nigger moon. Sinner! Blood-burning moon. Sinner! Come out that fact’ry door. 2 Up from the deep dusk of a cleared spot on the edge of the forest a mellow glow arose and spread fan-wise into the low-hanging heavens. And all around the air was heavy with the scent of boiling cane. A large pile of cane-stalks lay like ribboned shadows upon the ground. A mule, harnessed to a pole, trudged lazily round and round the pivot of the grinder. Beneath a swaying oil lamp, a Negro alternately whipped out at the mule, and fed cane-stalks to the grinder. A fat boy waddled pails of fresh ground juice between the grinder and the boiling stove. Steam came from the copper boiling pan. The scent of cane came from the copper pan and drenched the forest and the hill that sloped to factory town, beneath its fragrance. It drenched the men in circle seated around the stove. Some of them chewed at the white pulp of stalks, but there was no need for them to, if all they wanted was to taste the cane. One tasted it in
  • 65. factory town. And from factory town one could see the soft haze thrown by the glowing stove upon the low-hanging heavens. Old David Georgia stirred the thickening syrup with a long ladle, and ever so often drew it off. Old David Georgia tended his stove and told tales about the white folks, about moonshining and cotton picking, and about sweet nigger gals, to the men who sat there about his stove to listen to him. Tom Burwell chewed cane-stalk and laughed with the others till someone mentioned Louisa. Till some one said something about Louisa and Bob Stone, about the silk stockings she must have gotten from him. Blood ran up Tom’s neck hotter than the glow that flooded from the stove. He sprang up. Glared at the men and said, “She’s my gal.” Will Manning laughed. Tom strode over to him. Yanked him up and knocked him to the ground. Several of Manning’s friends got up to fight for him. Tom whipped out a long knife and would have cut them to shreds if they hadnt ducked into the woods. Tom had had enough. He nodded to Old David Georgia and swung down the path to factory town. Just then, the dogs started barking and the roosters began to crow. Tom felt funny. Away from the fight, away from the stove, chill got to him. He shivered. He shuddered when he saw the full moon rising towards the cloud-bank. He who didnt give a godam for the fears of old women. He forced his mind to fasten on Louisa. Bob Stone. Better not be. He turned into the street and saw Louisa sitting before her home. He went towards her, ambling, touched the brim of a marvelously shaped, spotted, felt hat, said he wanted to say something to her, and then found that he didnt know what he had to say, or if he did, that he couldnt say it. He shoved his big fists in his overalls, grinned, and started to move off. “Youall want me, Tom?” “Thats what us wants, sho, Louisa.” “Well, here I am—” “An here I is, but that aint ahelpin none, all th same.” “You wanted to say something?..”
  • 66. “I did that, sho. But words is like th spots on dice: no matter how y fumbles em, there’s times when they jes wont come. I dunno why. Seems like th love I feels fo yo done stole m tongue. I got it now. Whee! Louisa, honey, I oughtnt tell y, I feel I oughtnt cause yo is young an goes t church an I has had other gals, but Louisa I sho do love y. Lil gal, Ise watched y from them first days when youall sat right here befo yo door befo th well an sang sometimes in a way that like t broke m heart. Ise carried y with me into th fields, day after day, an after that, an I sho can plow when yo is there, an I can pick cotton. Yassur! Come near beatin Barlo yesterday. I sho did. Yassur! An next year if ole Stone’ll trust me, I’ll have a farm. My own. My bales will buy yo what y gets from white folks now. Silk stockings an purple dresses—course I dont believe what some folks been whisperin as t how y gets them things now. White folks always did do for niggers what they likes. An they jes cant help alikin yo, Louisa. Bob Stone likes y. Course he does. But not th way folks is awhisperin. Does he, hon?” “I dont know what you mean, Tom.” “Course y dont. Ise already cut two niggers. Had t hon, t tell em so. Niggers always tryin t make somethin out a nothin. An then besides, white folks aint up t them tricks so much nowadays. Godam better not be. Leastawise not with yo. Cause I wouldnt stand f it. Nassur.” “What would you do, Tom?” “Cut him jes like I cut a nigger.” “No, Tom—” “I said I would an there aint no mo to it. But that aint th talk f now. Sing, honey Louisa, an while I’m listenin t y I’ll be makin love.” Tom took her hand in his. Against the tough thickness of his own, hers felt soft and small. His huge body slipped down to the step beside her. The full moon sank upward into the deep purple of the cloud-bank. An old woman brought a lighted lamp and hung it on the common well whose bulky shadow squatted in the middle of the
  • 67. road, opposite Tom and Louisa. The old woman lifted the well-lid, took hold the chain, and began drawing up the heavy bucket. As she did so, she sang. Figures shifted, restless-like, between lamp and window in the front rooms of the shanties. Shadows of the figures fought each other on the gray dust of the road. Figures raised the windows and joined the old woman in song. Louisa and Tom, the whole street, singing: Red nigger moon. Sinner! Blood-burning moon. Sinner! Come out that fact’ry door. 3 Bob Stone sauntered from his veranda out into the gloom of fir trees and magnolias. The clear white of his skin paled, and the flush of his cheeks turned purple. As if to balance this outer change, his mind became consciously a white man’s. He passed the house with its huge open hearth which, in the days of slavery, was the plantation cookery. He saw Louisa bent over that hearth. He went in as a master should and took her. Direct, honest, bold. None of this sneaking that he had to go through now. The contrast was repulsive to him. His family had lost ground. Hell no, his family still owned the niggers, practically. Damned if they did, or he wouldnt have to duck around so. What would they think if they knew? His mother? His sister? He shouldnt mention them, shouldnt think of them in this connection. There in the dusk he blushed at doing so. Fellows about town were all right, but how about his friends up North? He could see them incredible, repulsed. They didnt know. The thought first made him laugh. Then, with their eyes still upon him, he began to feel embarrassed. He felt the need of explaining things to them. Explain hell. They wouldnt understand, and moreover, who ever heard of a Southerner getting on his knees to any Yankee, or anyone. No sir. He was going to see Louisa to-night, and love her. She was lovely—in her way. Nigger way. What way was that? Damned if he knew. Must know. He’d known her long enough to
  • 68. know. Was there something about niggers that you couldnt know? Listening to them at church didnt tell you anything. Looking at them didnt tell you anything. Talking to them didnt tell you anything— unless it was gossip, unless they wanted to talk. Of course, about farming, and licker, and craps—but those werent nigger. Nigger was something more. How much more? Something to be afraid of, more? Hell no. Who ever heard of being afraid of a nigger? Tom Burwell. Cartwell had told him that Tom went with Louisa after she reached home. No sir. No nigger had ever been with his girl. He’d like to see one try. Some position for him to be in. Him, Bob Stone, of the old Stone family, in a scrap with a nigger over a nigger girl. In the good old days... Ha! Those were the days. His family had lost ground. Not so much, though. Enough for him to have to cut through old Lemon’s canefield by way of the woods, that he might meet her. She was worth it. Beautiful nigger gal. Why nigger? Why not, just gal? No, it was because she was nigger that he went to her. Sweet... The scent of boiling cane came to him. Then he saw the rich glow of the stove. He heard the voices of the men circled around it. He was about to skirt the clearing when he heard his own name mentioned. He stopped. Quivering. Leaning against a tree, he listened. “Bad nigger. Yassur, he sho is one bad nigger when he gets started.” “Tom Burwell’s been on th gang three times fo cuttin men.” “What y think he’s agwine t do t Bob Stone?” “Dunno yet. He aint found out. When he does— Baby!” “Aint no tellin.” “Young Stone aint no quitter an I ken tell y that. Blood of th old uns in his veins.” “Thats right. He’ll scrap, sho.” “Be gettin too hot f niggers round this away.” “Shut up, nigger. Y dont know what y talkin bout.”
  • 69. Bob Stone’s ears burned as though he had been holding them over the stove. Sizzling heat welled up within him. His feet felt as if they rested on red-hot coals. They stung him to quick movement. He circled the fringe of the glowing. Not a twig cracked beneath his feet. He reached the path that led to factory town. Plunged furiously down it. Halfway along, a blindness within him veered him aside. He crashed into the bordering canebrake. Cane leaves cut his face and lips. He tasted blood. He threw himself down and dug his fingers in the ground. The earth was cool. Cane-roots took the fever from his hands. After a long while, or so it seemed to him, the thought came to him that it must be time to see Louisa. He got to his feet and walked calmly to their meeting place. No Louisa. Tom Burwell had her. Veins in his forehead bulged and distended. Saliva moistened the dried blood on his lips. He bit down on his lips. He tasted blood. Not his own blood; Tom Burwell’s blood. Bob drove through the cane and out again upon the road. A hound swung down the path before him towards factory town. Bob couldnt see it. The dog loped aside to let him pass. Bob’s blind rushing made him stumble over it. He fell with a thud that dazed him. The hound yelped. Answering yelps came from all over the countryside. Chickens cackled. Roosters crowed, heralding the bloodshot eyes of southern awakening. Singers in the town were silenced. They shut their windows down. Palpitant between the rooster crows, a chill hush settled upon the huddled forms of Tom and Louisa. A figure rushed from the shadow and stood before them. Tom popped to his feet. “Whats y want?” “I’m Bob Stone.” “Yassur—an I’m Tom Burwell. Whats y want?” Bob lunged at him. Tom side-stepped, caught him by the shoulder, and flung him to the ground. Straddled him. “Let me up.” “Yassur—but watch yo doins, Bob Stone.”
  • 70. A few dark figures, drawn by the sound of scuffle stood about them. Bob sprang to his feet. “Fight like a man, Tom Burwell, an I’ll lick y.” Again he lunged. Tom side-stepped and flung him to the ground. Straddled him. “Get off me, you godam nigger you.” “Yo sho has started somethin now. Get up.” Tom yanked him up and began hammering at him. Each blow sounded as if it smashed into a precious, irreplaceable soft something. Beneath them, Bob staggered back. He reached in his pocket and whipped out a knife. “Thats my game, sho.” Blue flash, a steel blade slashed across Bob Stone’s throat. He had a sweetish sick feeling. Blood began to flow. Then he felt a sharp twitch of pain. He let his knife drop. He slapped one hand against his neck. He pressed the other on top of his head as if to hold it down. He groaned. He turned, and staggered towards the crest of the hill in the direction of white town. Negroes who had seen the fight slunk into their homes and blew the lamps out. Louisa, dazed, hysterical, refused to go indoors. She slipped, crumbled, her body loosely propped against the woodwork of the well. Tom Burwell leaned against it. He seemed rooted there. Bob reached Broad Street. White men rushed up to him. He collapsed in their arms. “Tom Burwell....” White men like ants upon a forage rushed about. Except for the taut hum of their moving, all was silent. Shotguns, revolvers, rope, kerosene, torches. Two high-powered cars with glaring search-lights. They came together. The taut hum rose to a low roar. Then nothing could be heard but the flop of their feet in the thick dust of the road. The moving body of their silence preceded them over the crest of
  • 71. the hill into factory town. It flattened the Negroes beneath it. It rolled to the wall of the factory, where it stopped. Tom knew that they were coming. He couldnt move. And then he saw the search- lights of the two cars glaring down on him. A quick shock went through him. He stiffened. He started to run. A yell went up from the mob. Tom wheeled about and faced them. They poured down on him. They swarmed. A large man with dead-white face and flabby cheeks came to him and almost jabbed a gun-barrel through his guts. “Hands behind y, nigger.” Tom’s wrist were bound. The big man shoved him to the well. Burn him over it, and when the woodwork caved in, his body would drop to the bottom. Two deaths for a godam nigger. Louisa was driven back. The mob pushed in. Its pressure, its momentum was too great. Drag him to the factory. Wood and stakes already there. Tom moved in the direction indicated. But they had to drag him. They reached the great door. Too many to get in there. The mob divided and flowed around the walls to either side. The big man shoved him through the door. The mob pressed in from the sides. Taut humming. No words. A stake was sunk into the ground. Rotting floor boards piled around it. Kerosene poured on the rotting floor boards. Tom bound to the stake. His breast was bare. Nails scratches let little lines of blood trickle down and mat into the hair. His face, his eyes were set and stony. Except for irregular breathing, one would have thought him already dead. Torches were flung onto the pile. A great flare muffled in black smoke shot upward. The mob yelled. The mob was silent. Now Tom could be seen within the flames. Only his head, erect, lean, like a blackened stone. Stench of burning flesh soaked the air. Tom’s eyes popped. His head settled downward. The mob yelled. Its yell echoed against the skeleton stone walls and sounded like a hundred yells. Like a hundred mobs yelling. Its yell thudded against the thick front wall and fell back. Ghost of a yell slipped through the flames and out the great door of the factory. It fluttered like a dying thing down the single street of factory town. Louisa, upon the step before her home, did not hear it,
  • 72. but her eyes opened slowly. They saw the full moon glowing in the great door. The full moon, an evil thing, an omen, soft showering the homes of folks she knew. Where were they, these people? She’d sing, and perhaps they’d come out and join her. Perhaps Tom Burwell would come. At any rate, the full moon in the great door was an omen which she must sing to: Red nigger moon. Sinner! Blood-burning moon. Sinner! Come out that fact’ry door.
  • 74. S SEVENTH STREET Money burns the pocket, pocket hurts, Bootleggers in silken shirts, Ballooned, zooming Cadillacs, Whizzing, whizzing down the street-car tracks. EVENTH STREET is a bastard of Prohibition and the War. A crude- boned, soft-skinned wedge of nigger life breathing its loafer air, jazz songs and love, thrusting unconscious rhythms, black reddish blood into the white and whitewashed wood of Washington. Stale soggy wood of Washington. Wedges rust in soggy wood... Split it! In two! Again! Shred it! .. the sun. Wedges are brilliant in the sun; ribbons of wet wood dry and blow away. Black reddish blood. Pouring for crude-boned soft-skinned life, who set you flowing? Blood suckers of the War would spin in a frenzy of dizziness if they drank your blood. Prohibition would put a stop to it. Who set you flowing? White and whitewash disappear in blood. Who set you flowing? Flowing down the smooth asphalt of Seventh Street, in shanties, brick office buildings, theaters, drug stores, restaurants, and cabarets? Eddying on the corners? Swirling like a blood-red smoke up where the buzzards fly in heaven? God would not dare to suck black red blood. A Nigger God! He would duck his head in shame and call for the Judgment Day. Who set you flowing? Money burns the pocket, pocket hurts, Bootleggers in silken shirts, Ballooned, zooming Cadillacs, Whizzing, whizzing down the street-car tracks.
  • 76. R RHOBERT HOBERT wears a house, like a monstrous diver’s helmet, on his head. His legs are banty-bowed and shaky because as a child he had rickets. He is way down. Rods of the house like antennæ of a dead thing, stuffed, prop up in the air. He is way down. He is sinking. His house is a dead thing that weights him down. He is sinking as a diver would sink in mud should the water be drawn off. Life is a murky, wiggling, microscopic water that compresses him. Compresses his helmet and would crush it the minute that he pulled his head out. He has to keep it in. Life is water that is being drawn off. Brother, life is water that is being drawn off. Brother, life is water that is being drawn off. The dead house is stuffed. The stuffing is alive. It is sinful to draw one’s head out of live stuffing in a dead house. The propped-up antennæ would cave in and the stuffing be strewn .. shredded life- pulp .. in the water. It is sinful to have one’s own head crushed. Rhobert is an upright man whose legs are banty-bowed and shaky because as a child he had rickets. The earth is round. Heaven is a sphere that surrounds it. Sink where you will. God is a Red Cross man with a dredge and a respiration-pump who’s waiting for you at the opposite periphery. God built the house. He blew His breath into its stuffing. It is good to die obeying Him who can do these things. A futile something like the dead house wraps the live stuffing of the question: how long before the water will be drawn off? Rhobert does not care. Like most men who wear monstrous helmets, the pressure it exerts is enough to convince him of its practical infinity. And he cares not two straws as to whether or not he will ever see his wife and children again. Many a time he’s seen them drown in his dreams and has kicked about joyously in the mud for days after. One
  • 77. thing about him goes straight to the heart. He has an Adam’s-apple which strains sometimes as if he were painfully gulping great globules of air .. air floating shredded life-pulp. It is a sad thing to see a banty-bowed, shaky, ricket-legged man straining the raw insides of his throat against smooth air. Holding furtive thoughts about the glory of pulp-heads strewn in water... He is way down. Down. Mud, coming to his banty knees, almost hides them. Soon people will be looking at him and calling him a strong man. No doubt he is for one who has had rickets. Lets give it to him. Lets call him great when the water shall have been all drawn off. Lets build a monument and set it in the ooze where he goes down. A monument of hewn oak, carved in nigger-heads. Lets open our throats, brother, and sing “Deep River” when he goes down. Brother, Rhobert is sinking. Lets open our throats, brother, Lets sing Deep River when he goes down.
  • 78. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com