Object Orientation Abstraction and Data Structures Using Scala Second Edition Lacher PDF Download
Object Orientation Abstraction and Data Structures Using Scala Second Edition Lacher PDF Download
https://textbookfull.com/product/object-orientation-abstraction-
and-data-structures-using-scala-second-edition-lacher/
https://textbookfull.com/product/a-beginners-guide-to-scala-
object-orientation-and-functional-programming-second-edition-
john-hunt/
https://textbookfull.com/product/object-oriented-data-structures-
using-java-4th-edition-dale/
https://textbookfull.com/product/a-beginners-guide-to-scala-
object-orientation-and-functional-programming-john-hunt/
https://textbookfull.com/product/learning-concurrent-programming-
in-scala-learn-the-art-of-building-intricate-modern-scalable-and-
concurrent-applications-using-scala-second-edition-prokopec/
Mastering Go create Golang production applications
using network libraries concurrency and advanced Go
data structures Second Edition Tsoukalos
https://textbookfull.com/product/mastering-go-create-golang-
production-applications-using-network-libraries-concurrency-and-
advanced-go-data-structures-second-edition-tsoukalos/
https://textbookfull.com/product/practical-object-oriented-
design-an-agile-primer-using-ruby-second-edition-metz/
https://textbookfull.com/product/modern-programming-made-easy-
using-java-scala-groovy-and-javascript-second-edition-adam-l-
davis/
https://textbookfull.com/product/problem-solving-in-data-
structures-algorithms-using-c-first-edition-jain/
https://textbookfull.com/product/data-structures-using-c-2nd-
edition-reema-thareja-oxford-publication-2014-reema-thareja/
OBJECT-ORIENTATION,
ABSTRACTION, AND
DATA STRUCTURES
USING
SCALA
SECOND EDITION
CHAPMAN & HALL/CRC
TEXTBOOKS IN COMPUTING
Series Editors
This series covers traditional areas of computing, as well as related technical areas, such as
software engineering, artificial intelligence, computer engineering, information systems, and
information technology. The series will accommodate textbooks for undergraduate and gradu-
ate students, generally adhering to worldwide curriculum standards from professional societ-
ies. The editors wish to encourage new and imaginative ideas and proposals, and are keen to
help and encourage new authors. The editors welcome proposals that: provide groundbreaking
and imaginative perspectives on aspects of computing; present topics in a new and exciting
context; open up opportunities for emerging areas, such as multi-media, security, and mobile
systems; capture new developments and applications in emerging fields of computing; and
address topics that provide support for computing, such as mathematics, statistics, life and
physical sciences, and business.
Published Titles
OBJECT-ORIENTATION,
ABSTRACTION, AND
DATA STRUCTURES
USING
SCALA
SECOND EDITION
Mark C. Lewis
Lisa L. Lacher
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2017 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been
made to publish reliable data and information, but the author and publisher cannot assume responsibility for the valid-
ity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or uti-
lized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopy-
ing, microfilming, and recording, or in any information storage or retrieval system, without written permission from the
publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://
www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For
organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
and the CRC Press Web site at
http://www.crcpress.com
Contents
Preface xxv
vii
viii Contents
11 Networking 369
11.1 TCP and UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
11.2 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
11.2.1 TCP Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
11.2.2 UDP Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
11.2.3 Streams from Sockets . . . . . . . . . . . . . . . . . . . . . . . . . 373
xii Contents
14 Refactoring 449
14.1 Smells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
14.2 Refactorings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
14.2.1 Built-in Refactoring Methods . . . . . . . . . . . . . . . . . . . . . 453
14.2.2 Introduce Null Object . . . . . . . . . . . . . . . . . . . . . . . . . 454
14.2.3 Add and Remove Parameter . . . . . . . . . . . . . . . . . . . . . 454
14.2.4 Cures for Switch Statements . . . . . . . . . . . . . . . . . . . . . 455
14.2.5 Consolidate Conditional Expression . . . . . . . . . . . . . . . . . 456
14.2.6 Convert Procedural Design to Objects . . . . . . . . . . . . . . . . 457
14.2.7 Encapsulate Collection . . . . . . . . . . . . . . . . . . . . . . . . 457
14.2.8 Push Down or Pull Up Field or Method . . . . . . . . . . . . . . . 458
14.2.9 Substitute Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . 458
Contents xiii
15 Recursion 461
15.1 Refresher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
15.2 Project Integration: A Maze . . . . . . . . . . . . . . . . . . . . . . . . . . 462
15.2.1 The Recursive Approach . . . . . . . . . . . . . . . . . . . . . . . 462
15.2.2 Graphical Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
15.2.3 Longest Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
15.2.4 Optimizing the Maze . . . . . . . . . . . . . . . . . . . . . . . . . 471
15.3 Graph Traversals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
15.4 Divide and Conquer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
15.4.1 Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
15.4.2 Quicksort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
15.4.3 Formula Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
15.5 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
15.5.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 488
15.5.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
15.5.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
16 Trees 493
16.1 General Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
16.1.1 Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
16.1.2 Traversals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
16.2 Project Integration: Formula Parsing . . . . . . . . . . . . . . . . . . . . . 498
16.2.1 Formula Tree Traversals and In-Order Traversal . . . . . . . . . . 502
16.3 Binary Search Trees: Binary Trees as Maps . . . . . . . . . . . . . . . . . 503
16.3.1 Order Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
16.3.2 Immutable BSTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
16.4 End of Chapter Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
16.4.1 Summary of Concepts . . . . . . . . . . . . . . . . . . . . . . . . . 514
16.4.2 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
16.4.3 Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
Bibliography 625
Index 627
List of Figures
1 This figure shows the relationships between the chapters in this book to
help you pick which ones you want to cover, and in what order. . . . . . . xxviii
1.1 The Scala API looks like this when viewing scala.collection.immutable.List.
The right column shows the various objects, classes, and traits. Selecting
one shows you the visible members inside of it. This is generated using
ScalaDoc on the library code. . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.1 This is a simple example of a UML use case diagram. Actors are drawn as
stick figures. The system being analyzed is a box. The ways in which the
actors use the system are drawn as circles. . . . . . . . . . . . . . . . . . . 61
2.2 This shows the UML class diagram for the Student class from section 2.2
along with a class for a course that contains multiple students. . . . . . . 62
2.3 This figure shows a use case diagram for a potential bank application that
models the customer-facing aspects of a bank. . . . . . . . . . . . . . . . . 64
2.4 This figure shows a class diagram for a potential bank application that
models the customer-facing aspects of a bank. . . . . . . . . . . . . . . . . 65
4.1 This figure shows a limited set of options for the subtyping relationships of
animals as a UML diagram. . . . . . . . . . . . . . . . . . . . . . . . . . . 118
4.2 This is a simple class diagram showing subtypes of fruit. . . . . . . . . . . 119
4.3 This class diagram for fruit adds some methods that we might want and
how they might be overridden in the subclasses. . . . . . . . . . . . . . . . 120
4.4 Diagram of general subtype relationships in Scala. This figure has been
adapted from a similar figure in Programming in Scala by Odersky, Spoon,
and Venners [10]. The thick lines with full arrowheads indicate a subtyping
relationship. The thin lines with an open arrowhead indicate an implicit
conversion. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
4.5 This UML class diagram shows what is commonly called the diamond prob-
lem. The challenge with this construct is that it can lead to significant
ambiguity. Different languages have different ways of dealing with this. . . 134
5.1 This is a use case diagram for our drawing program. . . . . . . . . . . . . 150
5.2 This is a simple diagram of what we want our GUI to look like when we are
done with the project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
5.3 This class diagram shows the most of the classes/traits that are relevant
to the ScalaFX scene graph. . . . . . . . . . . . . . . . . . . . . . . . . . . 154
5.4 This is the window that pops up when you run the full version of FirstGUI. 155
xvii
xviii List of Figures
5.5 This is the window that pops up when you run DrawingMain. . . . . . . . 160
5.6 This is a first cut class diagram for our drawing project. . . . . . . . . . . 161
5.7 This is the window that pops up when you run the more complete version
of DrawingMain. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
6.1 This is a UML diagram of the main types in the scala.collection package.
The collection types we have dealt with, including List[A] and Array[A],
have been under the Seq[A] part of the hierarchy. . . . . . . . . . . . . . . 186
6.2 This is a UML diagram of the main types in the scala.collection.immutable
package. This image is significantly simplified. If you look in the API you
will see that most of the types inherit from multiple other types. . . . . . 187
6.3 This is a UML diagram of the main types in the scala.collection.mutable
package. This image is significantly simplified. If you look in the API you
will see that most of the types inherit from multiple other types. . . . . . 188
7.1 This figure shows a graphical representation of the meaning of O. The solid
line represents g(n), which would be a measure of the amount of compu-
tation done for an input size n. The dotted line is the function, c × f (n),
where we want to say that g(n) is O(f (n)). This plot labels a position m,
above which the dotted curve is always above the solid curve. . . . . . . . 216
7.2 This figure shows a graphical representation of an Array-based stack and
how it changes over several operations. The stack stores data in the Array
and uses an integer index to keep track of the position of the top. . . . . . 219
7.3 This figure shows a graphical representation of an Array-based queue and
how it changes over several operations. The queue stores data in the Array
and uses integer indexes to keep track of the front and back. . . . . . . . . 223
7.4 This figure shows a graphical representation of an Array-based queue when
it needs to grow on an enqueue. The queue is seen as empty if front==back.
For that reason, the grow operation should happen when the last slot will
be filled. In addition to allocating a bigger Array, the copy operation needs
to move elements of the Array around and alter the location of front and
back. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
7.5 This is what Eclipse shows when a JUnit test is run and all tests are passed.
A green bar means that everything is good. If you get a red bar, then one
or more tests have failed and they will be listed for you. . . . . . . . . . . 228
7.6 This is the drawing program after adding a maze and executing a breadth-
first solution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
7.7 This figures shows in a graphical way what happens when a breadth-first
search is run. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
8.1 This figure shows frequencies, transistor counts, and core counts for x86
processors produced between 1978 and 2016. The log scale on the plot makes
it so that exponential curves appear as straight lines. The dotted lines show
fits to the full transistor count data and the frequency data through 2000.
Clock speeds shown are the highest release for each chip. . . . . . . . . . . 245
8.2 This UML diagram shows the main types in the three different parallel
collection packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
8.3 This is a screen capture of the drawing program with a Mandelbrot image. 270
8.4 This figure shows a single method call between two objects in a basic se-
quence diagram. The key thing to note is that the thread goes with the call.
So when you call methods, the thread weaves around and between objects. 274
List of Figures xix
8.5 This figure shows three objects and two method calls in a basic sequence
diagram that illustrates how a race condition occurs. Even if the objects
properly encapsulate and protect their values, you still have to use synchro-
nization to prevent race conditions. . . . . . . . . . . . . . . . . . . . . . . 275
8.6 This figure shows three actors and two messages in a basic sequence diagram
that illustrates how the actor model prevents race conditions. Each actor
has only a single thread, and messages are processed sequentially, so as
long as mutable state is confined to a single actor, you cannot have race
conditions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
8.7 This figure shows the organization of the actor hierarchy that we are build-
ing in the example in this section. . . . . . . . . . . . . . . . . . . . . . . . 284
8.8 This is a screen capture of the drawing program with a Julia set image. . 292
11.1 This figure shows the different use cases for the socket/stream-based chat
program that we want to write. . . . . . . . . . . . . . . . . . . . . . . . . 374
11.2 This is a screen shot of the RMI chat client with two users connected. . . 387
11.3 This is a screen shot of the collaboration window. On the left is a column
showing shared drawings. On the bottom is a chat area. The main portion
is a shared sketch region where different collaborators can draw using some
simple types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
12.1 This figure shows what happens when you do an insert and a remove from
an array-based implementation of the list ADT. Note how operations near
the beginning have to do many copies, but operations near the end do not. 407
12.2 This figure shows the basic structure of some different forms of linked lists. 408
12.3 This figure shows what happens with insert and remove on a singly linked
list. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
12.4 This figure shows what happens with insert and remove on a doubly linked
list. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
13.1 This figure shows how we can do remove from an unsorted array-based
priority queue in O(1) operations after we have done an O(n) search to find
the highest-priority element. . . . . . . . . . . . . . . . . . . . . . . . . . . 435
13.2 This screen shot shows the output of the cell simulation Drawable. The
properties that are used are visible on the left side of the window. . . . . . 439
15.1 This is the drawing program with a sample graph created using DrawGraph. 479
16.1 This figure shows a sample tree with some of the nodes labeled. Node P is
the parent of nodes C, D, and E. D and E are siblings of C. Node P has a
depth of 1 and a height of 2, while node C has a depth of 2 and a height of
1. The size of node P is six, while the size of node C is 2. . . . . . . . . . . 494
16.2 This figure shows the same tree that was displayed in figure 16.1, but draws
arrows for the first-child, next-sibling approach to building the tree. . . . . 495
16.3 This figure shows the same tree that was displayed in figures 16.1 and
16.2. Here, all of the nodes are labeled with letters to aid the discussion of
traversal. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
16.4 This figure shows the recursion that happens when we parse the formula
3*(x-5)+x*x on the left side. On the right is the tree that we would want
to build from this formula. . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
xx List of Figures
16.5 This is an example of a binary search tree using integer value keys. Searching
for an element in the tree follows steps very much like those a binary search
would perform. The bold arrows show the path that would be taken in a
search for the value 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
16.6 This figure shows the creation of the BST from figure 16.5. Each element
is placed by running down the tree in the same manner as a search until
we hit a location where there is not a child. A new node with the value is
placed in that location. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
18.1 This figure shows an example of a binary heap. The numbers are priorities
with higher values being higher priority. Note that there is no problem with
duplicate priorities, unlike keys in a BST. There is also no order requirement
between siblings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
18.2 This figure shows the same heap as in figure 18.1 with subscripts that num-
ber the nodes in breadth-first order. Below that is an array with the elements
at those locations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
18.3 Adding a new element with a priority of 9 to the heap shown in figure 18.1
goes through the following steps. A bubble is added at the next location in
a complete tree. It moves up until it reaches a point where the new value
can be added without breaking the heap order. . . . . . . . . . . . . . . . 542
18.4 Calling dequeue on the heap at the end of figure 18.3 forces the tree to
go through the following steps. The last element is moved to a temporary
variable, and a stone is placed at the top of the heap. This stone sinks down
until it reaches a point where the temporary can stop without breaking heap
order. The stone always sinks in the direction of the higher-priority child.
If the children have equal priority, it does not matter which side the stone
goes to. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
18.5 This shows a pictorial representation of the alternate data structure that
can be used as an efficient priority queue for collision handling. The top
array keeps the heads of lists for different time brackets during the time
step. The left array is the heads of lists for different particles. All lists are
doubly linked so that nodes can be removed without finding the one before
it. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
19.1 The binary file holding the linked list has the following format. The be-
ginning of the file is a header with four values written as Longs. They are
the position of the head node, the position of the tail node, the number of
nodes, and the position of the first free node. . . . . . . . . . . . . . . . . 561
19.2 The nodes of a B-tree can each store a certain number of records. The
number of records is selected to match an optimal size for disk reads and
writes. Non-leaf nodes have references to children at the beginning, end,
and between each record. The records in a node are sorted by a key. In
addition, the nodes in children have to have key values that fall between
the keys of the records they are between, or just below and above for the
beginning and end children. B-trees are always balanced and require few
disk accesses to find a record, but they do potentially waste some space. . 565
List of Figures xxi
19.3 This figure illustrates how adds are done for B-trees. A) shows the tree from
figure 19.2 with the addition of a record whose key value is 75. The 75 is
simply placed in sorted order in a leaf because there is still space left in
that node. For B), a record with a key value of 82 has been added. It would
go right after the 75 record, but there is no more space in that node. Of the
five records that would be in the node, the 75 is the median so it is moved
into the parent and the other records are split into two different nodes. This
process can propagate to higher levels in the tree if the parent is also full.
A new level is created when the root node fills and has to split. . . . . . . 566
20.1 This figure shows an example set of points with a very non-uniform spatial
distribution. A regular grid is laid over this to make it clear how the point
density in the grid cells will vary dramatically. The grid size shown here
works well for many of the low-density regions where there are only a handful
of points per cell. A grid that only had a few points per cell in the high-
density regions would be a very fine grid with an extremely large fraction
of the cells being empty in the low-density areas. . . . . . . . . . . . . . . 574
20.2 This is a quadtree with a number of non-uniformly distributed points to
illustrate how the space is partitioned. For this example, each node is only
allowed to hold a single point. The key advantage of the tree-based approach
is that the resolution does not have to be uniform. Higher-density regions
can divide the space much more finely. . . . . . . . . . . . . . . . . . . . . 575
20.3 This is a kD-tree with a number of non-uniformly distributed points to
illustrate how the space is partitioned. For this example, each node can
hold up to three points. While this example only uses two dimensions, it is
simple to scale the kD-tree higher without adding overhead. . . . . . . . . 579
21.1 This figure shows single rotations to the left and the right. These rotations
can be used when a node becomes unbalanced because the outer grandchild
on the left or the right is too tall relative to the other subtree. . . . . . . . 589
21.2 This figure shows double rotations to the left-right and the right-left. These
rotations can be used when a node becomes unbalanced because the inner
grandchild is too tall. Note that each of these is simply two applications of
the rotations from figure 21.1 . . . . . . . . . . . . . . . . . . . . . . . . . 590
21.3 This figure shows two arrays and their possible tree representations. The
second was arrived at by adding the letter ‘t’ at index 5 of the first. In the
tree, each node has the value, a letter, drawn large with a preceding number
that is the size of the node and a following number that is the index. . . . 594
22.1 This figure shows a graphic representation of the idea behind a hash table.
Keys can be any type of data and are not necessarily ordered. The keys are
mapped, using some function that we call the hash function, to positions
in the storage array. There are many more possible keys than there are
locations in the array, so it is possible to have “collisions” where different
keys map to the same location. . . . . . . . . . . . . . . . . . . . . . . . . 610
xxii List of Figures
22.2 This figure illustrates the challenge that we run into when we have the
option to remove a key-value pair when using open addressing. The left
column shows our words and the value given by our hash function using the
division method for an array with 15 elements. The middle column shows
where all those keys would wind up in the table assuming linear probing.
The third column shows it with “a” removed, which would cause problems
if we go looking for “system.” . . . . . . . . . . . . . . . . . . . . . . . . . 618
List of Tables
0.1 This table shows which projects appear as options in each of the different
chapters. The ‘X’ represents a unique project description. An ‘S’ indicates
that there is a standard description for students to use their own implemen-
tation of a data structure in their project. . . . . . . . . . . . . . . . . . . . xxx
3.1 This table shows the precedence rules for operators in Scala. The precedence
is based on the first character in the operator. . . . . . . . . . . . . . . . . . 88
19.1 This table shows how many bytes are written to disk for each of the basic
value types using either DataOutputStream or RandomAccessFile. . . . . . 552
xxiii
Preface
Thank you for purchasing Object-Orientation, Abstraction, and Data Structures Using
Scala. This book is intended to be used as a textbook for a second or third semester
course in Computer Science. The contents of this book are an expanded second edition
of the second half of Introduction to the Art of Programming Using Scala. The first half
of that book became Introduction to Programming and Problem Solving Using Scala. This
book assumes that the reader has previous programming experience, but not necessarily in
Scala. The introductory chapter is intended to quickly bring the reader up to speed on the
Scala syntax. If you already know Scala, you can skim this chapter for a refresher or skip
it completely.
To the Student
The field of Computer Science has remarkable depth. It has to in order to match the
capabilities and flexibility of the machines that we call “computers”. Your first steps into the
field should have shown you how to structure logic and break down problems, then write up
your instructions for how to solve the problems in the formal syntax of some programming
language. In this book, we want to build upon those capabilities. We want to give you
the tools of object orientation to help you structure solutions to larger, more complex
problems without experiencing mental overload in doing so. We also want to expand on
your knowledge of abstraction so that you can make your code more powerful and flexible.
Of course, all of this is implemented using the Scala programming language, which provides
powerful constructs for expressing both object orientation and abstraction.
One of the key ways that we illustrate these concepts is through the creation of data
structures. Data structures form one of the cornerstones of the field of computer science, and
understanding them is essential for anyone who wants to be an effective software developer.1
We strive to show you not only how these data structures can be written, but the strengths
and weaknesses of each one, so that you can understand when you should consider choosing
different ones.
This book also spends a fair bit of time looking at libraries that provide the functionality
you need to do real programming. This includes things like GUIs, multithreading, and
networking. The goal is to put you in a position where you can solve problems that you are
interested in. These are also vitally important topics that grow in importance every day, so
gaining a basic understanding of them early is something that we think is important.
There are a number of resources available to you that help support the mate-
rial in this book. Much of this material is kept at the book’s website, http://www.
programmingusingscala.net/. We teach our own classes using a flipped format, and there
1 One of the authors recently optimized a section of a professional program that was taking 90 seconds
to run down to 0.3 seconds simply by using more appropriate data structures for key operations.
xxv
xxvi Preface
are video playlists for every chapter in this book available at https://www.youtube.com/
channel/UCEvjiWkK2BoIH819T-buioQ. Even if you are not using this book as part of a
course that uses a flipped format, the videos can do something significant that the book
cannot. They can show you the dynamic aspect of programming. Much of the video content
is live coding where we talk through our thought processes as we construct code. This is a
valuable aspect of programming that prose on paper struggles to communicate. Where the
videos are weak is in total depth of coverage. The book goes into much deeper detail on
many topics than what is covered in the videos.
The playlists on the YouTube channel go beyond the contents of this book. They include
the previous book and a number of more advanced topics. We also post more videos on a
regular basis, so feel free to subscribe to see when additional material becomes available.
Lastly, we have put all of the code in this book in a GitHub repository (https:
//github.com/MarkCLewis/OOAbstractDataStructScala) that you can go through and
pull down. The code is organized into separate packages for each chapter. Occasionally
in the text we present changes to earlier code without showing the entire file that re-
sults. Finished files can always be found in the code repository. We have done the same
for the code written in the videos. It is available at https://github.com/MarkCLewis/
OOAbstractDataStructScalaVideos.
We hope you enjoy this step on your journey to learning computer science and developing
your programming skills.
To the Instructor
Why Scala?
Probably the most distinguishing aspect of this book is the choice of Scala as the imple-
mentation language. As an instructor, you inevitably feel multiple influences when selecting
the language to use for introductory courses, especially given that you do not really want to
focus on language at all. You want to focus on concepts, but you know that those concepts
have to be taught in some language so that students can actually get practice. So you re-
ally want a language that will let you teach the concepts that you feel are most important
without getting in the way. Given this, the next obvious question is, why is Scala a good
language for teaching the concepts covered in this book?
There are several pieces to this answer associated with the different groups of concepts
that are covered in this book. First, Scala is an object-oriented language. Much of the
discussion of the language focuses on the functional features of the language, and while
those are wonderful in many ways and the expressivity they bring is used in this book on
many occasions, the reality is that Scala is more object oriented than it is functional. It is
more object oriented than Java, C++, Python, or most of the other languages one might
consider using to teach this material, with the possible exception of Smalltalk and Ruby. All
values in Scala are objects, which simplifies many details compared to languages where there
are distinctions between primitives and objects.2 There is no concept of “static”, which is
replaced by singleton object declarations which fit much better in the OO model. Even the
functions are really just objects with an implementation of the apply method.
2 A favorite example of this is converting between a commonly used type. In Java, why do you say i =
(int)x, but i = Integer.parseInt(s)? Why can you not make an ArrayList<int> but you can make an
int[] which has very different syntax? In Scala you can say x.toInt and s.toInt and you can use the same
Int type with all of your collections which all have uniform syntax.
Preface xxvii
Scala provides many different tools for creating abstraction in code. You have the stan-
dard OO approaches through polymorphism with inheritance and type parameters. You also
have the approaches found in functional languages created by the ease of passing functions
around. Support for pass-by-name adds yet another tool for creating abstraction in code
that is not available in many languages.
Some instructors will also be happy to know that these abstraction tools are all im-
plemented in a statically typed manner. We consider knowledge of type systems to be an
integral part of programming and CS in general. Static type systems have their own formal
logic that can help to structure student thinking and there are certain topics that simply
cannot be taught in dynamically typed languages.
These factors all contribute to the use of Scala for teaching data structures. The language
works very well for teaching students how to construct type-safe collections of their own
from the ground up.
Beyond the keywords in the title of the book, we like to introduce interesting and useful
libraries, which are abundant in both Scala and the broader JVM environment. The ability
to use the advanced multithreading libraries in Scala while also leaning on Java libraries for
things like networking, is remarkably advantageous.
One of the key features of Scala is that it is not opinionated. It lets you do things your
way. Some people lament that in professional environments. However, in the classroom, that
means that you can teach what and how you want. You can use declarative constructs if
you want to focus on higher level thinking or use imperative constructs when you want your
students to have to deal with the details. A general idea behind Scala is that there is no
silver bullet for most problems in computer science, so a language should provide you with
options to do things in the way that you feel is best. We believe that this matters as much
in the classroom as in other venues.
Lastly, there are the influences beyond pedagogy. There are considerations of how a
language fits into the full departmental curriculum and how it impacts students outside
of your curriculum. Scala works well beyond just the introductory courses. It is broadly
used in web development, has a significant range of tools for parallelism, and thanks to the
Spark library, it has become a dominant force in the area of data analytics. As a result,
it is not hard to envision Scala being used in later courses in the curriculum. As for real-
world usage, we would argue that Scala sits in the sweet spot for pedagogy. It is being
broadly used outside of academia. At the time of this writing, it was number 14 on the
latest RedMonk language ranking, sitting at roughly equal position on both the GitHub
and StackOverflow axes of that ranking. This is high enough that you can point students,
parents, and colleagues to real-world usage. However, it is far enough down that students
are less likely to be able to find answers to all of your programming assignments with a
simple Google search.
While there is no perfect language for anything, we do believe that for these reasons,
and likely others that we have missed, Scala is a good option for introductory programming
courses.
FIGURE 1: This figure shows the relationships between the chapters in this book to help
you pick which ones you want to cover, and in what order.
Exploring the Variety of Random
Documents with Different Content
MASTER PATTERN 4 passed on^to higher races* Hence the
persons now living in a relatively low race are either laggards or late-
comers* This is the general rule, though there are said to be
instances in which a soul belonging to a more advanced life-wave
takes incarnation in a body belonging to an earlier evolutionary
type* Note well that this occult doctrine cannot he twisted to mean
that members of surviving races like the Australian aborigines orthe
natives of Patagonia or African pygmies are in any sense less human
than members of the later waves of evolution. No supercilious racism
is possible for one who (truly understands the occult law of
evolution. All through the age-long history of evolution- -no matter
what the forms taken by the li fe- wave- - the guiding and directing
impulse has come through the human Higher Soul. The evolution of
the animal kingdom is not only a prelude to the appearance of man*
It is the continuous, unbroken history of what the Bible calls Ada -v
Yet this archetypal A«^am, the Christos, though in' perfect union
with the Father (as modern translations of the New Testament
render what older versions put as ‘‘one wfth the Father’*), though
present eSr. /
MASTER PATTERN 4 as the nucleus of every human Higher
Soul or Ego, must in a sense be distinguished from thwt Ego. The
archetypal Adam or Christos is the Sun of the Higher Soul, even as
the intuition of the poet taught him when he wrote the familiar
.hymn, ‘‘Sun of my Soul.*' What you and I call our own ggo is in
perfect union with the central Sun, as that, in turn, is in perfect
union with the One Self, the Indivisible.^ Nor dan anything destroy
that Union. The whole ghastly error founded on a mi s t r ansi at
ion- - 1 he ridiculous ideg that any human being can lose his soul--is
utter nonsense. Not, ‘‘What shall it profit a man if he gain the whole
world, and lose his own soul?** is what Jesus asked, but, "What
shall it profit a man if he gain the whole world, and lose his owin'
life?** The truth is bad enough, without making it worse. For one
can, for a time, lose ’one’s life. Not just the life of the physical body,
but that grasp of the integration of finer vehicles which keeps an Ego
in touch with his own life-wave, and enables him to advance with it
through the stages of evolution. This is the dreadful *3* second
death* * of which there are guarded hints in the New Testament. -4
MASTER PATTERN 4 Not annihilation. Nat damnation in the
ordinary sense. The second death is a breaking of. the tie between
the Ego and the lower, persisting, finer vehicles. Not often does this
occur, and the catastrophe is by no means irremediable. Yet the
danger is grave enough to justify a solemn warning against the one
human tendency which is the beginning of the way leading to this
disaster. This is the tendency toward preoccupation .with standards
of success, fame or glory, based on the superficial appearances of
this world. The position of Ageless Wisdom is. that even when
organic development is at the stage oi genus homo, there is still a
group -soul. It is the Nephesh, the Animal or Vital Soul we have
found placed in Yesod, as the foundation for the outer physical
vehicle. For the human Vital Soul is more like a stratum of the total
Animal Soul than l.ike a separate entity. It might be compared to the
upper level of the waters of a great sea, with deep on deep below,
growing darker the farther one descends from the surface. 4 Human
personalities are as waves on the upper surface of this sea,
reflecting the sky overhead, and glittering with the mirrored light -5
MASTER PATTERN 4 of the sun in that sky. A million million
reflections of that One Sun, the central Ego of the whole human^
race; and that Ego, in turn,; a projection and true- image of the One
SELF, Yekhidah in Kether. Up tb a certain point in the progress of
elmbodied life from lower to higher levels, the Ego shapes its
vehicles without even a glimmer of knowledge as to what goes on
finding expression in the consciousness of the particular vehicle.
That is, t he expression of the Ego is almost wholly through the
Ego's direct action on the Vital Soul. At the stage to. which the
human race has now advanced- -but a moment in eternity,; though
it is many . miileniums of miileniums in time-- there comes a great
opportunity. In genus homo, the Ego has brought into manifestation
a beihg able, because of its brain and nervous organization, to
express knowledge of two things o'f paramount importance: 1. Of its
own interior, yet superior, spiritual nature; 2. Of the character of the
evolutionary process. Because of this possibility of the human race,
its more advanced members, in every generation, have been -6
MASTER PATTERN 4 able to learn the answers to three
great questions: 1. Whence came I? 2. How did I get here? 3. Who
am I? The answers to these questions provide also the answer to a
fourth and culminating inquiry: 4. Where am I going? The answers
are not beliefs. They are not convictions. They are assured and
definite knowledge, and they lead to a most important discovery.
Man, of all the inhabitants of the earth, is the only being able to
participate consciously in the evolutionary process. Ants herd their
insect cows, but no ant colony ever bred a new' type of aphis. Man
is able to transform wolves and jackals into friends and companions,
and can develop new strains at will. Man transmutes grass into
wheat, and fills the world with plants which are a direct result of his
taking thought, and controlling the tide of life as it flows through
plant forms. A few men, observing nature and roan's work with her,,
have learned the lesson. They see that the human race itself is
subject to gradual change by the long-term processes of eugenics
and modification of environ-7
MASTER PATTERN 4 ment. Fewer still, watching more
closely, have hit on yet another way to participate in conscious
evolution--but even in t&is supposedly enlightened age, only a
minority are capable of grasping the bare idea-let alone the
technique for carrying it out. By -this we mean that a small number
of persons in any generation are able, not only to conceive the
possibility of the development of genus homo into something beyond
the natural man, but have power also to effect that transformation
and transmutation in themselves. Having done so, they wield powers
greater even than those attributed to them by wild romance.
Greater, but not quite the same. Ilence they who know the marks of
a genuine adept or Master will never be deceived by tales written by
pretenders to higher knowledge. The outstanding account of a real
Master is the life of Jesus, fragmentary as the Gospel record is.
Compare the simple, yet compelling Gospel history with the marvels
recounted in some of the New Testament Apocrypha, especially
those written to meet the demand for fuller knowledge of Jesus’
childhood. Then you will understand, if you have any critical sense,
why the canon of the -8
MASTER PATTERN 4 New Testament rejects these products
of a not very vivid imagination. Yet most of the Apocrypha are
superior to some modern stories about Masters. When one has
grasped the significance of Jesus’ life and works, the ‘‘Shasta side-
shows’’ seem tawdry indeed; and the vague accounts of
‘.'initiations’* which serve as escape literature for a certain type of
mind suffer sadly by comparison with the narrative of the initiation--
mis-called temp tat ion- in the wilderness. blasters there are, and
their mastery consists in their perfect response to the impulses
coming to them from the archetypal Ego which is the nucleus of
every human Higher Soul. They who have attained to conscious
union with that Ego have the Philosophers' Stone, the great secret of
transmutation. This they attain by three processes, illustrated in
Tarot by three Keys, which we shall consider in this and the two
following lessons. The first step toward union with the Higher Soul is
represented in Tarot by Key 15. This Key corresponds to the path
leading upward on the Tree of Life, from the eighth cirele, the seat
of Intellect, to the sixth, the abode of the Ego.
MASTER PATTERN 4 Before explaining this picture, let us
establish a principle. All our progress upward is a reaction or
response to the downward and outward impulse in the path we
ascend. Thus we go upward in eonsciousness--or inward--because of
the influence flowing down from a higher and more interior level. In
early stages of the Great Work we may be unaware of this. Then it
will seem to us that we struggle, of our own volition and effort, to
reach the heights. Yet the universal testimony of the wise who have
really attained those heights is that the power which enables them
to climb comes really from within and from above. In the last
analysis, say they, we are drawn upward. Now, the descending
influence from Tiphareth is pictured as the Devil. It is a symbol of
what is behind all our plans for making something better than it is
now, behind all our endeavors to effect improvements, behind all our
projects for building more stately mansions for our souls. It is,
moreover, a picture of the aspect of the Ego which is presented to
our mindSiWhen those minds are untrained, when they mistake
superficial appearances for realities, when they are at the very
beginning of the Path of Liberation.
MASTER PATTERN 4 Once in Psalms we read that, the fear
of the Lord is the beginning of wisdom. Once in, Proverbs we find a
similar quotation, but this one says the fear of the Lord is the
beginning of knowledge. In both places,, the, ‘‘fear of the Lord'’
means just what is pictured in Tarot as the Devil. The Devil i
MASTER PATTERN 4 in nature essentially inimical to man.
Our mistake is an evidence of faulty use of the power seated, in the
eighth Sephirah. It is an unski lful, blundering employment of
intellect. Mark Twain it was who said no religion can exist without a
devil. The Bible goes farther, though it veils its doctrine by various
devices. Actually, what is pictured by Key 15 is what providers
incentive for living. It is what led you to study this course. You seek
knowledge here because, at some period in your life-history, you
have faced a problem which was too much for you. Perhaps you
reached the conclusion, ‘‘Everything seems to be against me. ' *
That was your Ego, trying to make you aware of yourself and of
itself by the method of getting you into a difficulty. Thus the story. of
Jesus' initiation says he was led by the Spirit into the wilderness, to
be tempted by the calumniator. To be tried by the challenge, “If you,
are, as you believe, a Son of God, give us this proof. ' ' Study Jesus'
temptations, apd you will find patterns of tests we all must meet.
Physical hunger, the thirst for power, the desire to make a
“convincing demonstration” by taking a
MASTER PATTERN 4 foolhardy risk.. No kind of human
temptation and testing but has its roots in one of t,hese. Nobody
enjoys these tests. ' You didn’t like yours. This accounts for the
growth of the notion that there is an actual devil. Way back down
the path of human evolution, every difficulty seemed to be the work
of a hidden enemy. Thus primitive worship is always devil worship,
the propitiation of a dangerous and jealous adversary by means of
sacrifice and flattery^Nor is the ' 1‘ god* ’ worshipped by millions
today much less of a devil. Actually, every obstacle is a test of our
powers. Every seemihg evil is a distorted image of an op*portunity.
The distortion, remember, lies always in man’s mind. Our devils are
projections of our faulty reasoning. Because thinking 'is work, it
seems easier to pretend there's no use trying, inasmuch as some
powerful devil will surely thwart all our endeavors to overcome the
difficulty. Medicine didn’t amount to much while men were
persuaded illness was caused by witches or by evil spirits. Psychiatry
didn’t come into being until there were human intellects brave
enough to -13
MASTER PATTERN 4 At the outset, it is always apparently
easier to go on believing a lie confirmed by tradition than it is to
think out a new truth which destroys the lie. To think is to break up
a lot of comfortable habits., We dodge it when we can, and no
dodge is commoner than that of inventing a devil. Small wonder that
beginners at thinking conjure up big and little devils to account for
their troubles! Even when we know better, it's easy to slip into this
error. Yet where is one new thing, one improvement over former
methods, one real step forward in human progress which cannot be
traced to some man's brave facing of a devil of opposition? The
discovery of the remedy begins with more accurate analysis of the
disease, with the substitution of right use of our intellectual powers
for lazy, superficial acceptance of outward appearances. It is not in
our devils, but in ourselves, that we are underlings. Big or little,
devils have just one power, and that is beneficent. They make us
think, and analyze, and seek a way out. Until the next lesson, then,
summon a little courage, and pick out one of your devils. Not too
big, at -14
MASTER PATTERN 4 first. Despise not the day of small
devils. Remember, “Sufficient unto the day is the evil thereof. ” Then
examine your devil. Subject the appearance of evil and adversity to
careful analysis. Do this, and you will find behind every one of your
devils an opportunity which will lead you farther along the Way of
Liberation.
THE MASTER PATTERN LESSON FIVE SOMETHING WHICH
needs repeating again and again ist that in spite of all figures of
speech about ‘‘scaling the heights,’* or ‘‘seeking higher things, *' the
Way of Discovery traversed by occultists leads nowhere but within.
Some reefers of this lessen may know a practice c<.llcd in="" the=""
planes.="" one="" sits="" a="" chair.="" he="" imagines="" has=""
body="" of="" light.="" having="" formulated="" his="" image=""
this="" endeavors="" to="" send="" it="" straight="" upward=""
by="" an="" intense="" act="" will.="" when="" attains=""
proficiency="" finds="" himself="" on="" another="" plane=""
existence.="" result="" is="" not="" mere="" reaction=""
suggestion.="" no="" means="" wholly="" subjective=""
experience.="" experimenter="" visits="" what="" can="" be=""
described="" other="" way="" than="" as="" definite=""
localities.="" they="" have="" their="" own="" characteristic=""
features.="" scenery="" including="" vegetation="" rivers=""
trees="" mountains="" plains="" buildings="" and="" like.=""
inhabitants="" include="" human="" beings="" animals="" like=""
those="" we="" know="" creatures="" both="" animal="">
MASTER PATTERN 5 like, different from anything on earth.
Repeated experiments make it clear that these * ‘ localities’ * may
be revisited again and again. Conditions there are different from
those we know here; but, in their way, they are stable as those of
the physical plane. This is the field of existence associated with the
ninth Sephirah, TID^, Yesod. This Sephirah is named Yesod,
Foundation, because the inner plane corresponding to it is the actual
basis of all physical manifestation. It is the astral plane of modern
theosophy, the Sheol of the Hebrews, the Hades of the Greeks,
which we call the " hereafter. ” It is the ‘‘spirit world’’ whence come
all mediumistic manifestations, good, bad, and indifferent. Finally, it
is the natural habitat of the Vital Soul. This world of the living dead--
and of others besides them--is not somewhere else. It is right here.
We are living in it now, just as truly as we shall be after we discard
these physical bodies. We have lived in it during many periods of
discarnate life. We have emerged from it into incarnation, again and
again. We are in it, and of it, this very moment, and always. -2
MASTER PATTERN 5 Thus the experiment of * ' rising in the
planes’* owes its name to an illusion. So does what is called ' *
astral projection.*' To travel consciously in the astral plane, there is
no need for detaching your astral vehicle from your physical body. In
physical space and time, such detachment is possible, but it is most
dangerous. Physical time and space, however, have nothing to do
with the *' other world;** and even for such astral ‘ 'journeys’* as
apparently travelling from California to some distant place, say. New
York, and bringing back a correct report of conditions in the locality
visited, there is no need for an actual detachment of the higher
bodies from the physical vehicle. What really occurs is that the
center of consciousness is shifted from awareness of the physical
plane to awareness of the Vital Soul. The Vital Soul is the collective
subconsciousness of the whole human race. Every human being is a
center of this collective activity. To perceive what is happening at a
distance, one need not travel at all. One simply tunes in on the
wavelength, so to say, of some person, or perhaps of several
persons, living in the locality ** visited,**
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com