% Generated by Sphinx.
\def\sphinxdocclass{report}
\documentclass[letterpaper,10pt,english]{sphinxmanual}
\usepackage[utf8]{inputenc}
\DeclareUnicodeCharacter{00A0}{\nobreakspace}
\usepackage{cmap}
\usepackage[T1]{fontenc}
\usepackage{babel}
\usepackage{times}
\usepackage[Bjarne]{fncychap}
\usepackage{longtable}
\usepackage{sphinx}
\usepackage{multirow}


\title{SIGCSE Workshop on Scala}
\date{27-October-2014 16:15:35}
\release{1.0}
\author{Lewis, Läufer, and Thiruvathukal}
\newcommand{\sphinxlogo}{}
\renewcommand{\releasename}{Release}
\makeindex

\makeatletter
\def\PYG@reset{\let\PYG@it=\relax \let\PYG@bf=\relax%
    \let\PYG@ul=\relax \let\PYG@tc=\relax%
    \let\PYG@bc=\relax \let\PYG@ff=\relax}
\def\PYG@tok#1{\csname PYG@tok@#1\endcsname}
\def\PYG@toks#1+{\ifx\relax#1\empty\else%
    \PYG@tok{#1}\expandafter\PYG@toks\fi}
\def\PYG@do#1{\PYG@bc{\PYG@tc{\PYG@ul{%
    \PYG@it{\PYG@bf{\PYG@ff{#1}}}}}}}
\def\PYG#1#2{\PYG@reset\PYG@toks#1+\relax+\PYG@do{#2}}

\expandafter\def\csname PYG@tok@gd\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
\expandafter\def\csname PYG@tok@gu\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
\expandafter\def\csname PYG@tok@gt\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
\expandafter\def\csname PYG@tok@gs\endcsname{\let\PYG@bf=\textbf}
\expandafter\def\csname PYG@tok@gr\endcsname{\def\PYG@tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}}
\expandafter\def\csname PYG@tok@cm\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@vg\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@m\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@mh\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@cs\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}\def\PYG@bc##1{\setlength{\fboxsep}{0pt}\colorbox[rgb]{1.00,0.94,0.94}{\strut ##1}}}
\expandafter\def\csname PYG@tok@ge\endcsname{\let\PYG@it=\textit}
\expandafter\def\csname PYG@tok@vc\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@il\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@go\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.20,0.20,0.20}{##1}}}
\expandafter\def\csname PYG@tok@cp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@gi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}}
\expandafter\def\csname PYG@tok@gh\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
\expandafter\def\csname PYG@tok@ni\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.84,0.33,0.22}{##1}}}
\expandafter\def\csname PYG@tok@nl\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.13,0.44}{##1}}}
\expandafter\def\csname PYG@tok@nn\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
\expandafter\def\csname PYG@tok@no\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.38,0.68,0.84}{##1}}}
\expandafter\def\csname PYG@tok@na\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@nb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@nc\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
\expandafter\def\csname PYG@tok@nd\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.33,0.33,0.33}{##1}}}
\expandafter\def\csname PYG@tok@ne\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@nf\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.02,0.16,0.49}{##1}}}
\expandafter\def\csname PYG@tok@si\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.44,0.63,0.82}{##1}}}
\expandafter\def\csname PYG@tok@s2\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@vi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@nt\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.02,0.16,0.45}{##1}}}
\expandafter\def\csname PYG@tok@nv\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
\expandafter\def\csname PYG@tok@s1\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@gp\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
\expandafter\def\csname PYG@tok@sh\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@ow\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@sx\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
\expandafter\def\csname PYG@tok@bp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@c1\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@kc\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@c\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
\expandafter\def\csname PYG@tok@mf\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@err\endcsname{\def\PYG@bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}
\expandafter\def\csname PYG@tok@kd\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@ss\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.32,0.47,0.09}{##1}}}
\expandafter\def\csname PYG@tok@sr\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.14,0.33,0.53}{##1}}}
\expandafter\def\csname PYG@tok@mo\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@mi\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
\expandafter\def\csname PYG@tok@kn\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@o\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
\expandafter\def\csname PYG@tok@kr\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@s\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@kp\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@w\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
\expandafter\def\csname PYG@tok@kt\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.56,0.13,0.00}{##1}}}
\expandafter\def\csname PYG@tok@sc\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@sb\endcsname{\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@k\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
\expandafter\def\csname PYG@tok@se\endcsname{\let\PYG@bf=\textbf\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
\expandafter\def\csname PYG@tok@sd\endcsname{\let\PYG@it=\textit\def\PYG@tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}

\def\PYGZbs{\char`\\}
\def\PYGZus{\char`\_}
\def\PYGZob{\char`\{}
\def\PYGZcb{\char`\}}
\def\PYGZca{\char`\^}
\def\PYGZam{\char`\&}
\def\PYGZlt{\char`\<}
\def\PYGZgt{\char`\>}
\def\PYGZsh{\char`\#}
\def\PYGZpc{\char`\%}
\def\PYGZdl{\char`\$}
\def\PYGZhy{\char`\-}
\def\PYGZsq{\char`\'}
\def\PYGZdq{\char`\"}
\def\PYGZti{\char`\~}
% for compatibility with earlier versions
\def\PYGZat{@}
\def\PYGZlb{[}
\def\PYGZrb{]}
\makeatother

\begin{document}

\maketitle
\tableofcontents
\phantomsection\label{index::doc}
\includegraphics{scalalogo.png}



\begin{DUlineblock}{0em}
\item[] \textbf{Mark Lewis}
\item[] Trinity University
\item[] Department of Computer Science
\end{DUlineblock}

\begin{DUlineblock}{0em}
\item[] \textbf{Konstantin Läufer and George K. Thiruvathukal}
\item[] Loyola University Chicago
\item[] Department of Computer Science
\end{DUlineblock}


\chapter{Table of Contents}
\label{index:table-of-contents}\label{index:scala-workshop-at-sigcse}
\includegraphics{scalalogo.png}


\section{About Scala}
\label{intro:about-scala}\label{intro::doc}
``Scala is an object-functional programming and scripting language for general
software applications, statically typed, designed to concisely express
solutions in an elegant, type-safe and lightweight (low ceremonial) manner.
Scala has full support for functional programming (including currying, pattern
matching, algebraic data types, lazy evaluation, tail recursion, immutability,
etc.). It cleans up what are often considered poor design decisions in Java
(such as type erasure, checked exceptions, the non-unified type system) and
adds a number of other features designed to allow cleaner, more concise and
more expressive code to be written.'' {\hyperref[intro:scalawikipedia]{{[}ScalaWikipedia{]}}}

Scala has no connection to \emph{La Scala} or \emph{Teatro all Scala} (the world
renowned opera house in Milan), but we (especially Dr. Thiruvathukal) love the
name because it addresses the traditions of programming languages and scalable
computing, while \emph{La Scala} is the title of one of his favorite jazz piano
albums by Keith Jarrett, who often names his concerts by the venues where he
performs. {\hyperref[intro:lascalaconcert]{{[}LaScalaConcert{]}}}

We'd like to think that the Scala language represents the design ideal of being
``small and beautiful'' but also great for computer science and practical problem
solving. We hope you agree!

\includegraphics{640px-Milano-scalanotte_e.jpg}

Source is Wikimedia Commons {\hyperref[intro:lascala]{{[}LaScala{]}}}


\subsection{Why Scala?}
\label{intro:why-scala}

\subsubsection{Redmonk Language Rankings}
\label{intro:redmonk-language-rankings}
\includegraphics{lang-rank-114-wm.png}

Scala is ranked 13 on this year's listing. This comes courtesy of {\hyperref[intro:redmonkpl]{{[}RedmonkPL{]}}}


\subsubsection{Technology Radar}
\label{intro:technology-radar}
Thoughtworks maintains a resource known as the Technology Radar {[}TWTechRadar{]}. Four classifications:
\begin{itemize}
\item {} 
Adopt

\item {} 
Trial

\item {} 
Assess

\item {} 
Hold

\end{itemize}

Scala is listed under \emph{Adopt}.


\subsubsection{Language Complexity}
\label{intro:language-complexity}
See presentation for now, \href{http://goo.gl/Q68fA}{http://goo.gl/Q68fA}.


\section{Installing Scala}
\label{install:installing-scala}\label{install::doc}

\subsection{Prerequisite: JDK}
\label{install:prerequisite-jdk}
As a prerequisite to Scala development, we recommend that you install
the Oracle Java Development Kit (Java 7 SE 7u51 or later). While you
can work with OpenJDK and other VM implementations to run Scala, our
initial testing is that the best experience and performance comes from
the latest stable release of the Java 7 Platform.
\begin{itemize}
\item {} 
\href{http://www.oracle.com/technetwork/java/javase/downloads/}{Oracle Java Platform Downloads}

\end{itemize}


\subsection{Command-Line Tools}
\label{install:command-line-tools}
We do most of our CS1 instruction using command line tools. If you
want to go this route, you can perform a standard Scala 2.10.x
standalone install using your system's package manager or manually
from
\begin{itemize}
\item {} 
\href{http://www.scala-lang.org/download/}{http://www.scala-lang.org/download/}

\end{itemize}

This is generally a good choice for projects without external
dependencies.

For projects with external dependencies (such as unit testing), we
also recommend using sbt (Simple Build Tool for Scala). You can
install version 0.13.x or newer of sbt using your system's package
manager or manually from
\begin{itemize}
\item {} 
\href{http://www.scala-sbt.org/release/docs/Getting-Started/Setup.html}{http://www.scala-sbt.org/release/docs/Getting-Started/Setup.html}

\end{itemize}

You may also need to configure the paths on your machine to make these
tools easy to work with.


\subsection{Text Editors}
\label{install:text-editors}
To go along with the command-line tools, you will need a text editor
that you like to work with.
\begin{itemize}
\item {} 
On Linux, we recommend \href{http://www.vim.org/}{Vim} or \href{https://www.gnu.org/software/emacs/}{Emacs}.
OS X Terminal also supports both via the command line or via the
\href{https://code.google.com/p/macvim/}{MacVim} and \href{http://aquamacs.org/}{AquaMacs}
projects.

\item {} 
The \href{http://www.vim.org}{Sublime Text Editor} is also wildly popular among agile developers and
works on all major platforms. While not free/open source, it can be used for an indefinite period
for free (with only occasional nagging suggesting you upgrade to the paid version). George uses this
editor not only for writing Scala but also for editing reStructuredText (the source code for
these notes).

\end{itemize}


\subsection{IDE Option: JetBrains IntelliJ IDEA}
\label{install:ide-option-jetbrains-intellij-idea}
Many faculty teaching introductory CS courses prefer an Integrated
Development Environment (IDE). We recommend IntelliJ IDEA, which is
growing in popularity over Eclipse and preferred by many of us. You
can get the Community edition for free from the following URL and then
install the Scala plugin through the plugin manager.
\begin{itemize}
\item {} 
\href{http://www.jetbrains.com/idea/download/}{http://www.jetbrains.com/idea/download/}

\end{itemize}

The IntelliJ IDEA Scala plugin undergoing active development, and
there is a tradeoff between stability and features/bug fixes. For
advanced Scala development, you may find yourself wanting to be more
bleeding edge. To this end, we recommend the current early access
version:
\begin{itemize}
\item {} 
\href{http://confluence.jetbrains.com/display/IDEADEV/IDEA+13.1+EAP}{http://confluence.jetbrains.com/display/IDEADEV/IDEA+13.1+EAP}

\end{itemize}

When you install the Scala plugin through the plugin manager, you will
automatically get the version that matches that of IDEA. There are
still a few glitches, but it has gotten a lot better since
January 2014. In particular, compilation (and execution of Scala
worksheets) has become much faster.

To work around false compilation errors in Scala worksheets, we also
recommend a standalone installation of Scala (sufficient for projects
without external dependencies) or sbt.


\subsection{IDE Option: Eclipse Scala IDE}
\label{install:ide-option-eclipse-scala-ide}
The official Scala IDE is provided as an Eclipse bundle that has Scala
already installed. It will work on all platforms with very minor
differences. The following link will take you there.
\begin{itemize}
\item {} 
\href{http://scala-ide.org/download/sdk.html}{http://scala-ide.org/download/sdk.html}

\end{itemize}

\index{download}

\section{Downloading these Materials}
\label{download:downloading-these-materials}\label{download:index-0}\label{download::doc}

\subsection{scalaworkshop.com (Primary)}
\label{download:scalaworkshop-com-primary}

\begin{threeparttable}
\capstart\caption{Available Tutorial Formats}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Format
} & \textsf{\relax 
URL
}\\
\hline
Web Pages
 & 
\href{http://scalaworkshop.com/}{http://scalaworkshop.com/}
\\

Web Pages (offline ZIP)
 & 
\href{http://scalaworkshop.com/dist/html.zip}{http://scalaworkshop.com/dist/html.zip}
\\

PDF
 & 
\href{http://scalaworkshop.com/latex/sigcse-scala.pdf}{http://scalaworkshop.com/latex/sigcse-scala.pdf}
\\

ePub (Experimental)
 & 
\href{http://scalaworkshop.com/epub/sigcse-scala.epub}{http://scalaworkshop.com/epub/sigcse-scala.epub}
\\
\hline\end{tabulary}

\end{threeparttable}



\subsection{scalaworkshop.cs.luc.edu (Mirror)}
\label{download:scalaworkshop-cs-luc-edu-mirror}

\begin{threeparttable}
\capstart\caption{Available Tutorial Formats}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Format
} & \textsf{\relax 
URL
}\\
\hline
Web Pages
 & 
\href{http://scalaworkshop.cs.luc.edu/}{http://scalaworkshop.cs.luc.edu/}
\\

Web Pages (offline ZIP)
 & 
\href{http://scalaworkshop.cs.luc.edu/dist/html.zip}{http://scalaworkshop.cs.luc.edu/dist/html.zip}
\\

PDF
 & 
\href{http://scalaworkshop.cs.luc.edu/latex/sigcse-scala.pdf}{http://scalaworkshop.cs.luc.edu/latex/sigcse-scala.pdf}
\\

ePub (Experimental)
 & 
\href{http://scalaworkshop.cs.luc.edu/epub/sigcse-scala.epub}{http://scalaworkshop.cs.luc.edu/epub/sigcse-scala.epub}
\\
\hline\end{tabulary}

\end{threeparttable}



\subsection{Source Code Repositories}
\label{download:source-code-repositories}
The following table contains links to direct download the source code for all of the long examples in our tutorial. We note
that shorter, interactive sessions shown in the tutorial (especially the ones meant to be done simultaneously by the reader)
are not in any repository. You must copy/paste to try them out on your own!


\begin{threeparttable}
\capstart\caption{ZIP Format}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Description
} & \textsf{\relax 
URL
}\\
\hline
integration-scala
 & 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/get/default.zip}{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/get/default.zip}
\\

lcs-systolicarray
 & 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala/get/default.zip}{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala/get/default.zip}
\\

hpjpc
 & 
\href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java/get/default.zip}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java/get/default.zip}
\\

introcs-scala-examples
 & 
\href{https://bitbucket.org/loyolachicagocs\_books/introcs-scala-examples/get/default.zip}{https://bitbucket.org/loyolachicagocs\_books/introcs-scala-examples/get/default.zip}
\\

numerical-explorations-scala
 & 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/numerical-explorations-scala/get/default.zip}{https://bitbucket.org/loyolachicagocs\_plsystems/numerical-explorations-scala/get/default.zip}
\\
\hline\end{tabulary}

\end{threeparttable}


The following table contains links to the source code repository (usually Bitbucket but sometimes GitHub). You will need to
be fluent with version control clients (e.g. \code{hg} or \code{git}) to check out the code from these repositories.

\begin{notice}{note}{Note:}
This option is recommended for experts only!
\end{notice}


\begin{threeparttable}
\capstart\caption{Repositories}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Description
} & \textsf{\relax 
URL
}\\
\hline
integration-scala
 & 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala}
\\

lcs-systolicarray
 & 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala}
\\

hpjpc
 & 
\href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}
\\

introcs-scala-examples
 & 
\href{https://bitbucket.org/loyolachicagocs\_books/introcs-scala-examples}{https://bitbucket.org/loyolachicagocs\_books/introcs-scala-examples}
\\

numerical-explorations-scala
 & 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/numerical-explorations-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/numerical-explorations-scala}
\\
\hline\end{tabulary}

\end{threeparttable}


Alternately, you can clone \href{https://bitbucket.org/sigcse2013scala/notes}{https://bitbucket.org/sigcse2013scala/notes} and run the \code{fullmake.sh} script, which will
pull all examples (assuming \code{hg} is installed on your computer) into the \code{examples} subdirectory.


\subsection{Comments?}
\label{download:contact}\label{download:comments}
Please don't hesitate to contact the authors.


\begin{threeparttable}
\capstart\caption{Repositories}

\begin{tabulary}{\linewidth}{|L|L|}
\hline
\textsf{\relax 
Name
} & \textsf{\relax 
E-mail
}\\
\hline
Mark Lewis
 & 
\href{mailto:mlewis@trinity.edu}{mlewis@trinity.edu}
\\

Konstantin Läufer
 & 
\href{mailto:laufer@cs.luc.edu}{laufer@cs.luc.edu}
\\

George K. Thiruvathukal
 & 
\href{mailto:gkt@cs.luc.edu}{gkt@cs.luc.edu}
\\
\hline\end{tabulary}

\end{threeparttable}



\section{Scala in CS1}
\label{cs1::doc}\label{cs1:scala-in-cs1}
\begin{notice}{warning}{Warning:}
This section is still in draft form but is nearly complete in terms of examples, subject to editing.
There might still be a few rough spots. Comments welcome to \href{mailto:gkt@cs.luc.edu}{gkt@cs.luc.edu}.
\end{notice}

This is an elaboration of our Google presentation slides: \href{http://goo.gl/Q68fA}{http://goo.gl/Q68fA}.


\subsection{Motivating Scala in CS1}
\label{cs1:motivating-scala-in-cs1}\begin{itemize}
\item {} 
Programming in the small

\item {} 
REPL - Read-Evaluate-Print-Loop

\item {} 
Scripting Environment

\item {} 
Libraries allow for interesting code (JVM)

\item {} 
Static type checking

\item {} 
Uniform syntax

\item {} 
Everything is a method call

\item {} 
Powerful collections

\end{itemize}

Our motivation is to have the best of both worlds:
\begin{itemize}
\item {} 
Concise script-ability of languages like Python and Ruby

\item {} 
Static type checking in the small makes it (generally) easy to fix compilation errors

\end{itemize}

The emerging \emph{worksheet} model makes it possible to give students many
examples that just work and can be adapted to solve new problems.


\subsection{Getting Started}
\label{cs1:getting-started}
Like many \emph{agile} languages, Scala embraces the notion of being able to get started using
a REPL (Read-Evaluate-Print-Loop), which allows for interactive execution and spontaneous
feedback.

We're assuming the reader can set up Scala and Java (needed to run Scala, a language that
targets the JVM primarily). Once you have Scala and Java installed, you can open up an
interactive session using the \emph{command line}. (For those who don't prefer the command line,
especially on Windows, we recommend installing IntelliJ Community Edition and the Scala
plug-in. This will allow you to get an interactive session as well.)


\subsubsection{Hello, World}
\label{cs1:hello-world}
\begin{Verbatim}[commandchars=\\\{\}]
\$ scala-2.10
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0\_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala\textgreater{} println("Hello, World")
Hello, World
\end{Verbatim}


\subsubsection{Types - ``Lack'' of Primitives}
\label{cs1:types-lack-of-primitives}
\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{l+m+mi}{1}
\PYG{n}{res1}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{1}
\end{Verbatim}

In the following, the user types \code{1.} and then hits the \code{\textless{}tab\textgreater{}} key--known as
tab completion--to show the available operations and methods available for an \code{Int}.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{l+m+mf}{1.}\PYG{o}{\PYGZlt{}}\PYG{n}{tab}\PYG{o}{\PYGZgt{}}
\PYG{o}{\PYGZpc{}}              \PYG{o}{\PYGZam{}}              \PYG{o}{*}              \PYG{o}{+}              \PYG{o}{\PYGZhy{}}
\PYG{o}{/}              \PYG{o}{\PYGZgt{}}              \PYG{o}{\PYGZgt{}=}             \PYG{o}{\PYGZgt{}\PYGZgt{}}             \PYG{o}{\PYGZgt{}\PYGZgt{}\PYGZgt{}}
\PYG{o}{\PYGZca{}}              \PYG{n}{asInstanceOf}   \PYG{n}{isInstanceOf}   \PYG{n}{toByte}         \PYG{n}{toChar}
\PYG{n}{toDouble}       \PYG{n}{toFloat}        \PYG{n}{toInt}          \PYG{n}{toLong}         \PYG{n}{toShort}
\PYG{n}{toString}       \PYG{n}{unary\PYGZus{}+}        \PYG{n}{unary\PYGZus{}\PYGZhy{}}        \PYG{n}{unary\PYGZus{}\PYGZca{}}        \PYG{o}{\textbar{}}
\end{Verbatim}


\subsubsection{Literals are mostly what you expect}
\label{cs1:literals-are-mostly-what-you-expect}
Integers

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{a} \PYG{k}{=} \PYG{l+m+mi}{95}
\PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{95}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{b} \PYG{k}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{95}
\PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{95}
\end{Verbatim}

Octal and Hexadecimal

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} val c = 039
\textless{}console\textgreater{}:1: error: malformed integer number
       val c = 039
               \textasciicircum{}

scala\textgreater{} val c = 037
warning: there were 1 deprecation warning(s); re-run with -deprecation for details
c: Int = 31

scala\textgreater{} val d = 0xff
d: Int = 255

scala\textgreater{} val d = 0xffac
d: Int = 65452
\end{Verbatim}

Double and Float

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{e} \PYG{k}{=} \PYG{l+m+mf}{1.34e\PYGZhy{}7}
\PYG{n}{e}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{l+m+mf}{1.34E\PYGZhy{}7}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{f} \PYG{k}{=} \PYG{l+m+mf}{1.34e\PYGZhy{}7f}
\PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Float} \PYG{o}{=} \PYG{l+m+mf}{1.34E\PYGZhy{}7}
\end{Verbatim}


\subsubsection{Statements vs. Expressions}
\label{cs1:statements-vs-expressions}
Scala eschews statements as a general rule in favor of expressions (which produce values), owing to its functional heritage, which emphasizes the composition of functions to effect computation.

In practice, however, many expressions, however, behave like statements as they produce \code{Unit} as
a result.

A notable consequence of this language decision is that some constructs are not provided in
Scala, including the familiar break and continue (found in loops).


\subsubsection{Everything is an Object}
\label{cs1:everything-is-an-object}
Scala is not designed in a vacuum. Its heritage is one shared with Java, even if its ideas have value
above and beyond Java. Everything is achieved in Scala with \emph{objects}, although you can do a tremendous amount of programming before ever writing a \emph{class} per se.

There are two consequences to this decision:
\begin{itemize}
\item {} 
There are no primitive types per se. Every one of the literals discussed previously is an object.
This eliminates the need to distinguish \code{int} from \code{Integer} (a major pain point for Java prior
to boxing/unboxing support).

\item {} 
There are very few keywords in Scala. Even when you encounter something that you think is a keyword,
it is often just a method call. A really good example is the concept of mapping (map) from functional
programming, which is a method common to just about every Scala collection.

\end{itemize}

Let's look at a couple of examples of methods. Here is an example of how to see the methods available
to an \code{Int} instance:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{a}\PYG{o}{.}\PYG{o}{\PYGZlt{}}\PYG{n}{tab}\PYG{o}{\PYGZgt{}}
\PYG{o}{\PYGZpc{}}              \PYG{o}{\PYGZam{}}              \PYG{o}{*}              \PYG{o}{+}              \PYG{o}{\PYGZhy{}}
\PYG{o}{/}              \PYG{o}{\PYGZgt{}}              \PYG{o}{\PYGZgt{}=}             \PYG{o}{\PYGZgt{}\PYGZgt{}}             \PYG{o}{\PYGZgt{}\PYGZgt{}\PYGZgt{}}
\PYG{o}{\PYGZca{}}              \PYG{n}{asInstanceOf}   \PYG{n}{isInstanceOf}   \PYG{n}{toByte}         \PYG{n}{toChar}
\PYG{n}{toDouble}       \PYG{n}{toFloat}        \PYG{n}{toInt}          \PYG{n}{toLong}         \PYG{n}{toShort}
\PYG{n}{toString}       \PYG{n}{unary\PYGZus{}+}        \PYG{n}{unary\PYGZus{}\PYGZhy{}}        \PYG{n}{unary\PYGZus{}\PYGZca{}}        \PYG{o}{\textbar{}}
\end{Verbatim}

Where you see \code{\textless{}tab\textgreater{}}, you can use a feature known as \emph{tab completion} in the REPL to see the options
available to value \code{a}. You'll notice one thing immediately, especially if you are familiar with Java:
operator overloading! That's right, every operator is a method.

Let's use the \code{+} method:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{a}\PYG{o}{.}\PYG{o}{+}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}
\PYG{n}{res5}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{98}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{a} \PYG{o}{+} \PYG{l+m+mi}{3}
\PYG{n}{res6}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{98}
\end{Verbatim}

Let's convert an Int to a Float:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{b} \PYG{k}{=} \PYG{n}{a}\PYG{o}{.}\PYG{n}{toFloat}
\PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Float} \PYG{o}{=} \PYG{l+m+mf}{95.0}
\end{Verbatim}

You can also invoke methods like \code{toFloat} (which take no parameters) without using dots. We will
take advantage of this syntax as part of good Scala style (in many of our examples).

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{b} \PYG{k}{=} \PYG{n}{a}\PYG{o}{.}\PYG{n}{toFloat}
\PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Float} \PYG{o}{=} \PYG{l+m+mf}{95.0}
\end{Verbatim}

We're going to look at more \emph{advanced} objects later (Scala collections) but this should give you
a taste of what is possible.


\subsubsection{Tuples}
\label{cs1:tuples}
A language feature that was popularized (but not invented) by the Python language are tuples. Tuples
eliminate the need for unwanted uses of a class for grouping multiple values. Let's take a quick
look.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{t} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{)}
\PYG{n}{t}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Int}\PYG{o}{,} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{u} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mf}{3.0}\PYG{o}{,} \PYG{l+m+mf}{4.0}\PYG{o}{)}
\PYG{n}{u}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Double}\PYG{o}{,} \PYG{k+kt}{Double}\PYG{o}{)} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mf}{3.0}\PYG{o}{,}\PYG{l+m+mf}{4.0}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{v} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mf}{3.0}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{)}
\PYG{n}{v}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Double}\PYG{o}{,} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mf}{3.0}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{)}
\end{Verbatim}

Notice that Scala infers the type of each one of these value definitions.

When working with a tuple, you're really working with an object. You can inspect the methods that
are available using the tab completion method shown previously.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{t}\PYG{o}{.}
\PYG{n}{\PYGZus{}1}                \PYG{n}{\PYGZus{}2}                \PYG{n}{asInstanceOf}      \PYG{n}{canEqual}
\PYG{n}{copy}              \PYG{n}{isInstanceOf}      \PYG{n}{productArity}      \PYG{n}{productElement}
\PYG{n}{productIterator}   \PYG{n}{productPrefix}     \PYG{n}{swap}              \PYG{n}{toString}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{u}\PYG{o}{.}
\PYG{n}{\PYGZus{}1}                \PYG{n}{\PYGZus{}2}                \PYG{n}{asInstanceOf}      \PYG{n}{canEqual}
\PYG{n}{copy}              \PYG{n}{isInstanceOf}      \PYG{n}{productArity}      \PYG{n}{productElement}
\PYG{n}{productIterator}   \PYG{n}{productPrefix}     \PYG{n}{swap}              \PYG{n}{toString}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{v}\PYG{o}{.}
\PYG{n}{\PYGZus{}1}                \PYG{n}{\PYGZus{}2}                \PYG{n}{asInstanceOf}      \PYG{n}{canEqual}
\PYG{n}{copy}              \PYG{n}{isInstanceOf}      \PYG{n}{productArity}      \PYG{n}{productElement}
\PYG{n}{productIterator}   \PYG{n}{productPrefix}     \PYG{n}{swap}              \PYG{n}{toString}
\end{Verbatim}

You can inspect the components of a tuple by using the \code{\_1}, \code{\_2}, ... methods.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{t}\PYG{o}{.}\PYG{n}{\PYGZus{}1}
\PYG{n}{res9}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{3}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{t}\PYG{o}{.}\PYG{n}{\PYGZus{}2}
\PYG{n}{res10}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{4}
\end{Verbatim}

You'll obviously not want to use these names to refer to the components of a tuple. Using
pattern matching, you can extract the components of a tuple and \emph{bind} them to proper names.
For example, if your tuple represents an (x, y) pair, you are likely to use a match expression
like this:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{t} \PYG{k}{match} \PYG{o}{\PYGZob{}} \PYG{k}{case} \PYG{o}{(}\PYG{n}{x}\PYG{o}{,} \PYG{n}{y}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}(\PYGZdl{}x, \PYGZdl{}y)\PYGZdq{}}\PYG{o}{)} \PYG{o}{\PYGZcb{}}
\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{)}
\end{Verbatim}


\subsubsection{Semicolon Inferencing}
\label{cs1:semicolon-inferencing}
Python programmers already know and love not having to deal with semicolons. Scala follows
this excellent practice as well.

You can do this:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{x} \PYG{k}{=} \PYG{l+m+mi}{30}\PYG{o}{;}
\PYG{n}{x}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{30}
\end{Verbatim}

But this works just as well and is the preferred way to write Scala code:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{y} \PYG{k}{=} \PYG{l+m+mi}{30}
\PYG{n}{y}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{30}
\end{Verbatim}


\subsubsection{Simple Input (and Output)}
\label{cs1:simple-input-and-output}
Much like Python and Java, import can be used to experiment with library objects and functions, even
before you know how to create classes:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{import} \PYG{n+nn}{scala.tools.jline.console.ConsoleReader}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{input} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{ConsoleReader}
\PYG{n}{input}\PYG{k}{:} \PYG{k+kt}{scala}\PYG{k+kt}{.}\PYG{k+kt}{tools}\PYG{k+kt}{.}\PYG{k+kt}{jline}\PYG{k+kt}{.}\PYG{k+kt}{console}\PYG{k+kt}{.}\PYG{k+kt}{ConsoleReader} \PYG{o}{=} \PYG{n}{scala}\PYG{o}{.}\PYG{n}{tools}\PYG{o}{.}\PYG{n}{jline}\PYG{o}{.}\PYG{n}{console}\PYG{o}{.}\PYG{n+nc}{ConsoleReader}\PYG{k}{@}\PYG{l+m+mi}{3}\PYG{n}{ec642e5}
\end{Verbatim}

Then you can inspect the capabilities of the ConsoleReader by using tab completion (as shown before)

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{input}\PYG{o}{.}\PYG{n}{r}\PYG{o}{\PYGZlt{}}\PYG{n}{tab}\PYG{o}{\PYGZgt{}}
\PYG{n}{readCharacter}     \PYG{n}{readLine}          \PYG{n}{readVirtualKey}    \PYG{n}{redrawLine}
\PYG{n}{removeCompleter}   \PYG{n}{replace}           \PYG{n}{resetPromptLine}   \PYG{n}{restoreLine}
\end{Verbatim}

Now we look up more details on the \code{readLine()} methods, which is what we
want to do basic, line-oriented input (a common need in introductory
teaching).

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{input}\PYG{o}{.}\PYG{n}{readLine}\PYG{o}{\PYGZlt{}}\PYG{n}{tab}\PYG{o}{\PYGZgt{}}

\PYG{k}{def} \PYG{n}{readLine}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{String}
\PYG{k}{def} \PYG{n}{readLine}\PYG{o}{(}\PYG{n+nc}{Character}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{String}
\PYG{k}{def} \PYG{n}{readLine}\PYG{o}{(}\PYG{n+nc}{String}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{String}
\PYG{k}{def} \PYG{n}{readLine}\PYG{o}{(}\PYG{n+nc}{String}\PYG{o}{,} \PYG{n+nc}{Character}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{String}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{data} \PYG{k}{=} \PYG{n}{input}\PYG{o}{.}\PYG{n}{readLine}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Please enter some text: \PYGZdq{}}\PYG{o}{)}
\PYG{n+nc}{Please} \PYG{n}{enter} \PYG{n}{some} \PYG{n}{text}\PYG{k}{:} \PYG{k+kt}{Hello}\PYG{o}{,} \PYG{n+nc}{World}
\PYG{n}{data}\PYG{k}{:} \PYG{k+kt}{String} \PYG{o}{=} \PYG{n+nc}{Hello}\PYG{o}{,} \PYG{n+nc}{World}
\end{Verbatim}

You'll probably find it necessary to read through the Scala documentation, but
in a number of cases, the behavior is similar to what you've seen in other
language APIs. \code{readLine()} is pretty well known in Java circles. As you can
see above, \code{readLine(String)} gives us what we want: the ability to read
input with a prompt of sorts.


\subsubsection{val vs. var}
\label{cs1:val-vs-var}\begin{itemize}
\item {} 
Values (keyboard \code{val}) are used for immutable storage.

\item {} 
Variables (keyword \code{var}) are used for mutable storage.

\item {} 
You can think of this as the reemergence of \code{const} but it takes on a more powerful and predictable form in Scala than other languages that preceded it.

\item {} 
Scala thinking prefers val to var. So do we.

\item {} 
Interesting

\end{itemize}


\subsubsection{Scripts and Worksheets}
\label{cs1:scripts-and-worksheets}
Similar to modern scripting languages (e.g. Python and Ruby) and the original shell, you can create a
Scala script in a file, e.g. \code{myscript.scala} and run the script using the \code{scala} command.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{\PYGZdl{}} \PYG{n}{scala} \PYG{n}{myscript}\PYG{o}{.}\PYG{n}{scala}
\end{Verbatim}

You can also \emph{load} the script within the Scala REPL:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{\PYGZdl{}} \PYG{n}{scala}
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{:}\PYG{k+kt}{load} \PYG{k+kt}{myscript.scala}
\end{Verbatim}

We'll be taking advantage of this a bit more in our discussion about \code{sbt}, the Scala Build Tool.


\subsubsection{Conditional and Functions}
\label{cs1:conditional-and-functions}
Functional \(\rightarrow\) expressions

if expression

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{a} \PYG{k}{=} \PYG{l+m+mi}{25}
\PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{25}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{b} \PYG{k}{=} \PYG{l+m+mi}{30}
\PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{30}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{max} \PYG{k}{=} \PYG{k}{if} \PYG{o}{(}\PYG{n}{a} \PYG{o}{\PYGZgt{}} \PYG{n}{b}\PYG{o}{)} \PYG{n}{a} \PYG{k}{else} \PYG{n}{b}
\PYG{n}{max}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{30}
\end{Verbatim}

Contrast with:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{var} \PYG{n}{max} \PYG{k}{=} \PYG{l+m+mi}{0}
\PYG{n}{max}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{if} \PYG{o}{(}\PYG{n}{a} \PYG{o}{\PYGZgt{}} \PYG{n}{b}\PYG{o}{)}
     \PYG{o}{\textbar{}}   \PYG{n}{max} \PYG{k}{=} \PYG{n}{a}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{if} \PYG{o}{(}\PYG{n}{a} \PYG{o}{\PYGZgt{}} \PYG{n}{b}\PYG{o}{)} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}    \PYG{n}{max} \PYG{k}{=} \PYG{n}{a}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}} \PYG{k}{else} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}    \PYG{n}{max} \PYG{k}{=} \PYG{n}{b}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{max}
\PYG{n}{res4}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{30}
\end{Verbatim}

Note: Similar to other agile languages, you can enter compound statements and blocks of code in the REPL.
The \code{\textbar{}} is a continuation character to indicate that more input is expected. It's often best to use a
text editor once you start entering more complex fragments of code (especially more complicated than what
you see here).

Functions are front and center when it comes to Scala programming. Although object-functional, a pure function
can be written without the boilerplate associated with OOP. We're proponents of OOP but prefer to introduce
functional thinking and \emph{use} of objects prior to creating classes.

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} def square(x : Int) = x * x
square: (x: Int)Int


scala\textgreater{} square(25)
res6: Int = 625

scala\textgreater{} square(25.0)
\textless{}console\textgreater{}:12: error: type mismatch;
 found   : Double(25.0)
 required: Int
              square(25.0)
                     \textasciicircum{}
\end{Verbatim}

As expected, the second invocation of \code{square()} results in an error. Scala performs static type checking
in real time. That is, this is \emph{not} a run-time check.


\subsubsection{Function literals}
\label{cs1:function-literals}
Let's build on the \code{square()} example to see how easy it is to generate the first \code{n} squares. We'll use
this to show how you can use functions as parameters and to sensitize the use of Scala \emph{function literals},
which are used rather idiomatically in Scala programming.

We'll start by generating the first 25 values using a Scala range.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{n} \PYG{k}{=} \PYG{l+m+mi}{10}
\PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{10}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{first\PYGZus{}n} \PYG{k}{=} \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}
\PYG{n}{first\PYGZus{}n}\PYG{k}{:} \PYG{k+kt}{scala}\PYG{k+kt}{.}\PYG{k+kt}{collection}\PYG{k+kt}{.}\PYG{k+kt}{immutable}\PYG{k+kt}{.}\PYG{k+kt}{Range}\PYG{k+kt}{.}\PYG{k+kt}{Inclusive} \PYG{o}{=} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{,} \PYG{l+m+mi}{6}\PYG{o}{,} \PYG{l+m+mi}{7}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{10}\PYG{o}{)}
\end{Verbatim}

This shows how to map the \code{square()} function to the range of values.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{first\PYGZus{}n}\PYG{o}{.}\PYG{n}{map}\PYG{o}{(}\PYG{n}{square}\PYG{o}{)}
\PYG{n}{res16}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Vector}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{l+m+mi}{36}\PYG{o}{,} \PYG{l+m+mi}{49}\PYG{o}{,} \PYG{l+m+mi}{64}\PYG{o}{,} \PYG{l+m+mi}{81}\PYG{o}{,} \PYG{l+m+mi}{100}\PYG{o}{)}
\end{Verbatim}

This shows how to map a \emph{function literal} to the range of values.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{first\PYGZus{}n} \PYG{n}{map} \PYG{o}{(}\PYG{n}{n} \PYG{k}{=\PYGZgt{}} \PYG{n}{n} \PYG{o}{*} \PYG{n}{n}\PYG{o}{)}
\PYG{n}{res17}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Vector}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{l+m+mi}{36}\PYG{o}{,} \PYG{l+m+mi}{49}\PYG{o}{,} \PYG{l+m+mi}{64}\PYG{o}{,} \PYG{l+m+mi}{81}\PYG{o}{,} \PYG{l+m+mi}{100}\PYG{o}{)}
\end{Verbatim}

This shows how you can combine a function literal with a previously defined function:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{first\PYGZus{}n} \PYG{n}{map} \PYG{o}{(}\PYG{n}{n} \PYG{k}{=\PYGZgt{}} \PYG{n}{square}\PYG{o}{(}\PYG{n}{n}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res18}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Vector}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{l+m+mi}{36}\PYG{o}{,} \PYG{l+m+mi}{49}\PYG{o}{,} \PYG{l+m+mi}{64}\PYG{o}{,} \PYG{l+m+mi}{81}\PYG{o}{,} \PYG{l+m+mi}{100}\PYG{o}{)}
\end{Verbatim}

You can avoid having to name arguments in function literals using the \code{\_} parameter. This syntax is a
bit awkward to new programmers (and therefore should be introduced gently in CS1 courses) but allows
for concise (and sometimes clearer) expression, especially when used in a disciplined way.

Consider this code that creates the first n even numbers:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{l+m+mi}{10} \PYG{n}{map} \PYG{o}{(}\PYG{k}{\PYGZus{}} \PYG{o}{*} \PYG{l+m+mi}{2}\PYG{o}{)}
\PYG{n}{res26}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Vector}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{6}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{,} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{l+m+mi}{12}\PYG{o}{,} \PYG{l+m+mi}{14}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{18}\PYG{o}{,} \PYG{l+m+mi}{20}\PYG{o}{)}
\end{Verbatim}

You might be tempted to try this by doing the following:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{l+m+mi}{10} \PYG{n}{map} \PYG{o}{(}\PYG{k}{\PYGZus{}} \PYG{o}{+} \PYG{k}{\PYGZus{}}\PYG{o}{)}
\PYG{o}{\PYGZlt{}}\PYG{n}{console}\PYG{k}{\PYGZgt{}:}\PYG{l+m+mi}{11}\PYG{k}{:} \PYG{k+kt}{error}\PYG{k+kt}{:} \PYG{k+kt}{wrong} \PYG{k+kt}{number} \PYG{k+kt}{of} \PYG{k+kt}{parameters}\PYG{o}{;} \PYG{n}{expected} \PYG{k}{=} \PYG{l+m+mi}{1}
              \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{l+m+mi}{10} \PYG{n}{map} \PYG{o}{(}\PYG{k}{\PYGZus{}} \PYG{o}{+} \PYG{k}{\PYGZus{}}\PYG{o}{)}
\end{Verbatim}

Alas, it doesn't work. Why? Because each occurrence of \code{\_} corresponds to an expected parameter. In
this case, there would have to be pairs of values. Unfortunately, in the range 1 to 10, each value is an Int.

Default parameters and named parameters

Similar to other agile languages, Scala allows you to specify default parameter values. This is particularly
useful, especially when diving into object-oriented programming, but has uses even before then.

Consider this version of \code{square()}:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{square}\PYG{o}{(} \PYG{n}{x} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{k}{=} \PYG{n}{x} \PYG{o}{*} \PYG{n}{x}
\PYG{n}{square}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{x}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{Int}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{square}\PYG{o}{(}\PYG{o}{)}
\PYG{n}{res28}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{square}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}
\PYG{n}{res29}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{25}
\end{Verbatim}

Here we are creating a version that has a default value of zero, if the caller doesn't specify \code{x}. (This
is not necessarily intended to be pedagogically interesting but is effective, considering we spent most of
our time in this section looking at the \code{square()} function!)


\subsection{Early Collection, Arrays and Lists}
\label{cs1:early-collection-arrays-and-lists}
Scala has some very advanced and comprehensive collections libraries. For CS1
you can focus only on the simplest of these, beginning with Arrays and Lists.
In actually makes sense to introduce these before loops (and iteration in
general) in Scala for two reasons. First, the collections have many methods
that allow you to do standard tasks that would often go in loops. As such,
Scala code often doesn’t include all that many loops. Second, the for loop in
Scala is really a foreach type loop that works with collections so it makes
more sense to introduce it after the basic collections.


\subsubsection{Making Arrays and Lists}
\label{cs1:making-arrays-and-lists}
The simplest way to make an Array or a List is with the following syntax.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{3}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{)}
\PYG{n}{res0}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mf}{1.3}\PYG{o}{,}\PYG{l+m+mf}{4.2}\PYG{o}{,}\PYG{l+m+mf}{3.14}\PYG{o}{)}
\PYG{n}{res1}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Double}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mf}{1.3}\PYG{o}{,} \PYG{l+m+mf}{4.2}\PYG{o}{,} \PYG{l+m+mf}{3.14}\PYG{o}{)}
\end{Verbatim}

Note that the Array and List types take type parameters. These appear in
square brackets. It is standard across the Scala language that value arguments
appear in parentheses, type arguments appear in square brackets, and curly
braces are used to denote code blocks for complex expressions or statements.
Also note that as before, Scala’s type inference figures out the types for
these expressions.

\begin{notice}{note}{Note:}
Technically these are making calls to the apply methods of the Array and
List companion objects. The details of how that works don’t really matter
in CS1, but you can find them in the section on object-orientation under
CS2. We cover this topic later in our discussion of classes and
objects.
\end{notice}

You can also made longer arrays using the new syntax that one uses in Java.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{new} \PYG{n+nc}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{(}\PYG{l+m+mi}{100}\PYG{o}{)}
\PYG{n}{res2}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,}
\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,}
\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,}
\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,}
\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{)}
\end{Verbatim}

Here we need to specify the type and say how big the Array is. Array objects in
Scala are implemented as Java arrays and they have the same general
properties. Like Java Arrays, they are mutable and they can’t dynamically
change their size. Note that this approach to making Arrays is not the one
typically used in Scala because if the type is something like String you get
the same behavior you have in Java and all the values are initialized to null.
Later in this section we will see the fill and tabulate methods, which are
much less likely to produce a NullPointerException and are generally favored
over this style of creating a large Array.

Lists can be built using the \code{::} operator. We read \code{::} as \code{cons}, following the
tradition of Scheme (Lisp and ML. \code{::} is a right associative operator so it takes a
value on the left and a List on the right. For example:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{l+m+mi}{1}\PYG{o}{::}\PYG{l+m+mi}{2}\PYG{o}{::}\PYG{l+m+mi}{3}\PYG{o}{::}\PYG{l+m+mi}{4}\PYG{o}{::}\PYG{n+nc}{Nil}
\PYG{n}{res4}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{)}
\end{Verbatim}

The \code{Nil} object is a short name for an empty List. You can also use
\code{List()} (the empty list) in place of \code{Nil}. Note that the List type is a
singly-linked, \emph{immutable} list. So prepending as shown above is an efficient
operation. Also note that you can’t change values without making a new List
because it is immutable.

This form of building a List with \code{::} is probably most beneficial with
recursive functions and works very well in situations where you don’t know how
many values you will be working with.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{readNumbers}\PYG{o}{(}\PYG{n}{n}\PYG{k}{:}\PYG{k+kt}{Int}\PYG{o}{)}\PYG{k}{:}\PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{k}{if}\PYG{o}{(}\PYG{n}{n}\PYG{o}{\PYGZlt{}}\PYG{l+m+mi}{1}\PYG{o}{)} \PYG{n+nc}{Nil} \PYG{k}{else}
     \PYG{o}{\textbar{}} \PYG{n}{readInt} \PYG{o}{::} \PYG{n}{readNumbers}\PYG{o}{(}\PYG{n}{n}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{readNumbers}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{n}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{readNumbers}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}
\PYG{l+m+mi}{1}
\PYG{l+m+mi}{2}
\PYG{l+m+mi}{3}
\PYG{l+m+mi}{4}
\PYG{l+m+mi}{5}
\PYG{n}{res6}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{readUntilQuit}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:}\PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}} \PYG{k}{val} \PYG{n}{data} \PYG{k}{=} \PYG{n}{readLine}
     \PYG{o}{\textbar{}} \PYG{k}{if}\PYG{o}{(}\PYG{n}{data}\PYG{o}{!=}\PYG{l+s}{\PYGZdq{}quit\PYGZdq{}}\PYG{o}{)} \PYG{n}{data}\PYG{o}{.}\PYG{n}{toInt} \PYG{o}{::} \PYG{n}{readUntilQuit}\PYG{o}{(}\PYG{o}{)} \PYG{k}{else} \PYG{n+nc}{Nil}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}
\PYG{n}{readUntilQuit}\PYG{k}{:} \PYG{o}{(}\PYG{o}{)}\PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{readUntilQuit}\PYG{o}{(}\PYG{o}{)}
\PYG{l+m+mi}{1}
\PYG{l+m+mi}{2}
\PYG{l+m+mi}{3}
\PYG{l+m+mi}{4}
\PYG{l+m+mi}{5}
\PYG{n}{quit}
\PYG{n}{res7}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{)}
\end{Verbatim}


\subsubsection{Indexing/Traversing Arrays and Lists}
\label{cs1:indexing-traversing-arrays-and-lists}
You can get to values in an Array or a List by indexing with parentheses.

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} val arr = Array(6,8,2,4,1)
arr: Array[Int] = Array(6, 8, 2, 4, 1)

scala\textgreater{} val lst = List('g','e','o','r','g','e')
lst: List[Char] = List(g, e, o, r, g, e)

scala\textgreater{} arr(2)
res1: Int = 2

scala\textgreater{} lst(2)
res2: Char = o
\end{Verbatim}

The use of parentheses instead of square brackets keeps the syntax consistent.
(Having parentheses is the next best thing to square brackets as well. It is certainly
preferable to having an explicit method call as found in Java to access elements in
the array. We also note that the well-known math/science focused programming language,
FORTRAN, uses parentheses for subscripting!)

Neither the Array type, nor the List type have any special place in the Scala
syntax. They are both handled in the programming language just like any other
library code. The compiler does optimize Arrays to Java bytecode arrays, but
that is an implementation detail beyond the scope of our workshop.

You can also use the syntax you would expect to set the values of elements in
an Array. You can’t do this for Lists because they are immutable.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{arr}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{)} \PYG{k}{=} \PYG{l+m+mi}{99}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{arr}
\PYG{n}{res4}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{6}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{,} \PYG{l+m+mi}{99}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{)}
\end{Verbatim}

The common way to run through a List is using the head and tail methods. The
head method returns the first element of the List while tail returns the last
remaining after the first element. (Note that these can be called on an Array
as well, but tail will be very inefficient as it builds a new, shorter Array.)
The use of head and tail is particularly well suited for recursion.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{sumList}\PYG{o}{(}\PYG{n}{lst}\PYG{k}{:}\PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)}\PYG{k}{:}\PYG{k+kt}{Int} \PYG{o}{=} \PYG{k}{if}\PYG{o}{(}\PYG{n}{lst}\PYG{o}{.}\PYG{n}{isEmpty}\PYG{o}{)} \PYG{l+m+mi}{0} \PYG{k}{else}
     \PYG{o}{\textbar{}} \PYG{n}{lst}\PYG{o}{.}\PYG{n}{head}\PYG{o}{+}\PYG{n}{sumList}\PYG{o}{(}\PYG{n}{lst}\PYG{o}{.}\PYG{n}{tail}\PYG{o}{)}
\PYG{n}{sumList}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{lst}\PYG{k+kt}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)}\PYG{n+nc}{Int}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sumList}\PYG{o}{(}\PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{3}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{,}\PYG{l+m+mi}{5}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res5}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{15}
\end{Verbatim}

This same function can be defined using a match and patterns in the following
way.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{sumList}\PYG{o}{(}\PYG{n}{lst}\PYG{k}{:}\PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)}\PYG{k}{:}\PYG{k+kt}{Int} \PYG{o}{=} \PYG{n}{lst} \PYG{k}{match} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}} \PYG{k}{case} \PYG{n+nc}{Nil} \PYG{k}{=\PYGZgt{}} \PYG{l+m+mi}{0}
     \PYG{o}{\textbar{}} \PYG{k}{case} \PYG{n}{h}\PYG{o}{::}\PYG{n}{t} \PYG{k}{=\PYGZgt{}} \PYG{n}{h} \PYG{o}{+} \PYG{n}{sumList}\PYG{o}{(}\PYG{n}{t}\PYG{o}{)}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}
\PYG{n}{sumList}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{lst}\PYG{k+kt}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)}\PYG{n+nc}{Int}
\end{Verbatim}


\subsubsection{Standard Methods}
\label{cs1:standard-methods}
The collection types in Scala have a large number of methods defined on them.
We won’t list them here. Instead, you can look in the {\hyperref[cs1:scalaapi]{{[}ScalaAPI{]}}} for the
names and details. This is what you get when you use tab completion in the
REPL on a List.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{lst}\PYG{o}{.}\PYG{o}{\PYGZlt{}}\PYG{n}{tab}\PYG{o}{\PYGZgt{}}
\PYG{o}{++}                   \PYG{o}{++:}                  \PYG{o}{+:}
\PYG{o}{/:}                   \PYG{o}{/:\PYGZbs{}}                  \PYG{o}{:+}
\PYG{o}{::}                   \PYG{o}{:::}                  \PYG{o}{:\PYGZbs{}}
\PYG{n}{addString}            \PYG{n}{aggregate}            \PYG{n}{andThen}
\PYG{n}{apply}                \PYG{n}{applyOrElse}          \PYG{n}{asInstanceOf}
\PYG{n}{canEqual}             \PYG{n}{collect}              \PYG{n}{collectFirst}
\PYG{n}{combinations}         \PYG{n}{companion}            \PYG{n}{compose}
\PYG{n}{contains}             \PYG{n}{containsSlice}        \PYG{n}{copyToArray}
\PYG{n}{copyToBuffer}         \PYG{n}{corresponds}          \PYG{n}{count}
\PYG{n}{diff}                 \PYG{n}{distinct}             \PYG{n}{drop}
\PYG{n}{dropRight}            \PYG{n}{dropWhile}            \PYG{n}{endsWith}
\PYG{n}{exists}               \PYG{n}{filter}               \PYG{n}{filterNot}
\PYG{n}{find}                 \PYG{n}{flatMap}              \PYG{n}{flatten}
\PYG{n}{fold}                 \PYG{n}{foldLeft}             \PYG{n}{foldRight}
\PYG{n}{forall}               \PYG{n}{foreach}              \PYG{n}{genericBuilder}
\PYG{n}{groupBy}              \PYG{n}{grouped}              \PYG{n}{hasDefiniteSize}
\PYG{n}{head}                 \PYG{n}{headOption}           \PYG{n}{indexOf}
\PYG{n}{indexOfSlice}         \PYG{n}{indexWhere}           \PYG{n}{indices}
\PYG{n}{init}                 \PYG{n}{inits}                \PYG{n}{intersect}
\PYG{n}{isDefinedAt}          \PYG{n}{isEmpty}              \PYG{n}{isInstanceOf}
\PYG{n}{isTraversableAgain}   \PYG{n}{iterator}             \PYG{n}{last}
\PYG{n}{lastIndexOf}          \PYG{n}{lastIndexOfSlice}     \PYG{n}{lastIndexWhere}
\PYG{n}{lastOption}           \PYG{n}{length}               \PYG{n}{lengthCompare}
\PYG{n}{lift}                 \PYG{n}{map}                  \PYG{n}{mapConserve}
\PYG{n}{max}                  \PYG{n}{maxBy}                \PYG{n}{min}
\PYG{n}{minBy}                \PYG{n}{mkString}             \PYG{n}{nonEmpty}
\PYG{n}{orElse}               \PYG{n}{padTo}                \PYG{n}{par}
\PYG{n}{partition}            \PYG{n}{patch}                \PYG{n}{permutations}
\PYG{n}{prefixLength}         \PYG{n}{product}              \PYG{n}{productArity}
\PYG{n}{productElement}       \PYG{n}{productIterator}      \PYG{n}{productPrefix}
\PYG{n}{reduce}               \PYG{n}{reduceLeft}           \PYG{n}{reduceLeftOption}
\PYG{n}{reduceOption}         \PYG{n}{reduceRight}          \PYG{n}{reduceRightOption}
\PYG{n}{removeDuplicates}     \PYG{n}{repr}                 \PYG{n}{reverse}
\PYG{n}{reverseIterator}      \PYG{n}{reverseMap}           \PYG{n}{reverse\PYGZus{}:::}
\PYG{n}{runWith}              \PYG{n}{sameElements}         \PYG{n}{scan}
\PYG{n}{scanLeft}             \PYG{n}{scanRight}            \PYG{n}{segmentLength}
\PYG{n}{seq}                  \PYG{n}{size}                 \PYG{n}{slice}
\PYG{n}{sliding}              \PYG{n}{sortBy}               \PYG{n}{sortWith}
\PYG{n}{sorted}               \PYG{n}{span}                 \PYG{n}{splitAt}
\PYG{n}{startsWith}           \PYG{n}{stringPrefix}         \PYG{n}{sum}
\PYG{n}{tail}                 \PYG{n}{tails}                \PYG{n}{take}
\PYG{n}{takeRight}            \PYG{n}{takeWhile}            \PYG{n}{to}
\PYG{n}{toArray}              \PYG{n}{toBuffer}             \PYG{n}{toIndexedSeq}
\PYG{n}{toIterable}           \PYG{n}{toIterator}           \PYG{n}{toList}
\PYG{n}{toMap}                \PYG{n}{toSeq}                \PYG{n}{toSet}
\PYG{n}{toStream}             \PYG{n}{toString}             \PYG{n}{toTraversable}
\PYG{n}{toVector}             \PYG{n}{transpose}            \PYG{n}{union}
\PYG{n}{unzip}                \PYG{n}{unzip3}               \PYG{n}{updated}
\PYG{n}{view}                 \PYG{n}{withFilter}           \PYG{n}{zip}
\PYG{n}{zipAll}               \PYG{n}{zipWithIndex}
\end{Verbatim}

You might notice that there is a sum method, so the listSum written above is
something you never need to write. There are also methods for converting
between types such at toList and toArray.


\subsubsection{Higher Order Methods}
\label{cs1:higher-order-methods}
Some of the methods in that list are worth describing instead of leaving it to
the reader to explore the API. In particular, the most commonly used higher-
order methods, like \code{map} and \code{filter}, are used to a significant extent in Scala
programming. The \code{foreach} method is also helpful in a number of situations.

Higher-order methods are methods that take or return functions. In this
situation, we are considering methods that take a function as an argument. The
\code{filter} method, for example, takes a function that takes one argument of the
type of the collection and returns a Boolean. That function is called on every
element of the collection. A new collection is produced that contains only the
elements for which the function returned true. To see how this is used,
consider the following code where we filter a List of Ints in two different
ways.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{lst} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{6}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{,}\PYG{l+m+mi}{9}\PYG{o}{,}\PYG{l+m+mi}{1}\PYG{o}{,}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{8}\PYG{o}{,}\PYG{l+m+mi}{3}\PYG{o}{,}\PYG{l+m+mi}{7}\PYG{o}{)}
\PYG{n}{lst}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{6}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{7}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{lst}\PYG{o}{.}\PYG{n}{filter}\PYG{o}{(}\PYG{k}{\PYGZus{}} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{6}\PYG{o}{)}
\PYG{n}{res8}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{lst}\PYG{o}{.}\PYG{n}{filter}\PYG{o}{(}\PYG{k}{\PYGZus{}} \PYG{o}{\PYGZpc{}} \PYG{l+m+mi}{2} \PYG{o}{==} \PYG{l+m+mi}{0}\PYG{o}{)}
\PYG{n}{res9}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{6}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{)}
\end{Verbatim}

Both examples use the shorthand underscore syntax for writing the lambda
expressions/function literals. They could have been written using the longer
syntax as \code{n =\textgreater{} n\textless{}6} and \code{n =\textgreater{} n\%2 == 0} respectively.

Another higher-order method that is used extensively is the \code{map} method
(one of our favorites). The argument passed into \code{map} is a function that takes
the type of the collection and returns something. The return type could be the
same as the input type, but it could be different. The map method returns a
new collection of the return type of the function. A first example will use
the list of integers from above and make a collection that contains values
that are twice the original values.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{lst}\PYG{o}{.}\PYG{n}{map}\PYG{o}{(}\PYG{k}{\PYGZus{}}\PYG{o}{*}\PYG{l+m+mi}{2}\PYG{o}{)}
\PYG{n}{res10}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{12}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{,} \PYG{l+m+mi}{18}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{6}\PYG{o}{,} \PYG{l+m+mi}{14}\PYG{o}{)}
\end{Verbatim}

To show that the types can be different, this second example shows mapping
Strings to their length.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{words} \PYG{k}{=} \PYG{l+s}{\PYGZdq{}This is a sentence with words\PYGZdq{}}\PYG{o}{.}\PYG{n}{split}\PYG{o}{(}\PYG{l+s}{\PYGZdq{} \PYGZdq{}}\PYG{o}{)}
\PYG{n}{words}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{String}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{n+nc}{This}\PYG{o}{,} \PYG{n}{is}\PYG{o}{,} \PYG{n}{a}\PYG{o}{,} \PYG{n}{sentence}\PYG{o}{,} \PYG{k}{with}\PYG{o}{,} \PYG{n}{words}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{words}\PYG{o}{.}\PYG{n}{map}\PYG{o}{(}\PYG{k}{\PYGZus{}}\PYG{o}{.}\PYG{n}{length}\PYG{o}{)}
\PYG{n}{res0}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{8}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{)}
\end{Verbatim}

The \code{foreach} method takes a function and simply executes the function on all
the elements of the collection. While map and filter return new collections,
\code{foreach} is used for its side effects and returns \code{Unit}.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{words}\PYG{o}{.}\PYG{n}{foreach}\PYG{o}{(}\PYG{n}{println}\PYG{o}{)}
\PYG{n+nc}{This}
\PYG{n}{is}
\PYG{n}{a}
\PYG{n}{sentence}
\PYG{k}{with}
\PYG{n}{words}
\end{Verbatim}

There are other higher-order methods that are very accessible for CS1 students
such as \code{count}, \code{exists}, and \code{forall}, all of which take predicate functions on a
single argument. There are more complex methods like the \code{reduce} methods and
\code{fold} methods that can be very helpful, but which are more challenging for CS1
students to understand. We use these occasionally in this workshop but recommmend
that they be used sparingly and with an emphasis on clarity (as opposed to conciseness).


\subsubsection{Currying and By-Name Arguments}
\label{cs1:currying-and-by-name-arguments}
The best ways to create large Arrays and Lists in Scala are with the \code{fill} and
\code{tabulate} methods. These use some syntax that needs to be introduced. The first
element of new syntax is that these methods are \emph{curried}. This means that the
arguments are broken across multiple argument lists. So instead of having
\code{f(x,y)} you would have \code{f(x)(y)}. This is a common feature of functional
programming languages and it is done to allow functions to be partially
applied. (A partial application means that you apply the function to a subset
of the arguments, which results in a new function of the remaining arguments.)
The syntax for defining a curried function in Scala is fairly
straightforward.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{currySum}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:}\PYG{k+kt}{Int}\PYG{o}{)}\PYG{o}{(}\PYG{n}{y}\PYG{k}{:}\PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{=} \PYG{n}{x}\PYG{o}{+}\PYG{n}{y}
\PYG{n}{currySum}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{x}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{o}{(}\PYG{k+kt}{y}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{Int}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{currySum}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}
\PYG{n}{res2}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{8}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{plus3} \PYG{k}{=} \PYG{n}{currySum}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}\PYG{k}{\PYGZus{}}
\PYG{n}{plus3}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=\PYGZgt{}} \PYG{n+nc}{Int} \PYG{k}{=} \PYG{o}{\PYGZlt{}}\PYG{n}{function1}\PYG{o}{\PYGZgt{}}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{plus3}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}
\PYG{n}{res3}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{8}
\end{Verbatim}

The need for the underscore in the partially applied call removes ambiguity in
the Scala syntax. Often functions are curried in Scala to help with type
inference or to simplify the syntax for calling them.

The second new element of the syntax is pass-by-name arguments. By default,
variables in Scala are passed in a manner similar to Java. The variables are
references and the references are passed by-value. With pass-by-name
semantics, the code is passed more like a function instead of by-value.
Instead of being evaluated at the call point, the code is wrapped in a “thunk”
(a term that originated with Algol 60). Every time the variable is used,  the
code is executed. We specify that a parameter is pass-by-name using a rocket
with no arguments.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{multiplyThrice}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:} \PYG{o}{=\PYGZgt{}} \PYG{n+nc}{Double}\PYG{o}{)} \PYG{k}{=} \PYG{n}{x}\PYG{o}{*}\PYG{n}{x}\PYG{o}{*}\PYG{n}{x}
\PYG{n}{multiplyThrice}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{x}\PYG{k+kt}{:} \PYG{o}{=\PYGZgt{}} \PYG{k+kt}{Double}\PYG{o}{)}\PYG{n+nc}{Double}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{var} \PYG{n}{i} \PYG{k}{=} \PYG{l+m+mi}{5}
\PYG{n}{i}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{5}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{multiplyThrice}\PYG{o}{(}\PYG{n}{i}\PYG{o}{)}
\PYG{n}{res5}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{l+m+mf}{125.0}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{multiplyThrice}\PYG{o}{(}\PYG{o}{\PYGZob{}}\PYG{n}{i} \PYG{o}{+=} \PYG{l+m+mi}{1}\PYG{o}{;} \PYG{n}{i}\PYG{o}{\PYGZcb{}}\PYG{o}{)}
\PYG{n}{res6}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{l+m+mf}{336.0}
\end{Verbatim}

The first invocation of \code{multiplyThrice} does what one would expect, even though
the argument is passed by-name.

We use call-by-name for timing blocks of code in the Monte Carlo Pi example later
in this section. See {\hyperref[cs1:montecarlopi]{\emph{Monte Carlo  Calculation}}}.


\subsubsection{Fill and Tabulate}
\label{cs1:fill-and-tabulate}
The fill method, which is defined on the Array object, is...


\subsection{Recursion for Iteration}
\label{cs1:recursion-for-iteration}
\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{sum}\PYG{o}{(}\PYG{n}{n} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{k}{if} \PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{l+m+mi}{0} \PYG{k}{else} \PYG{n}{n} \PYG{o}{+} \PYG{n}{sum}\PYG{o}{(}\PYG{n}{n}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{sum}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{n}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{Int}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}
\PYG{n}{res0}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{res1}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{1}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{)}
\PYG{n}{res2}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{3}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}
\PYG{n}{res3}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{6}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{100}\PYG{o}{)}
\PYG{n}{res4}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{5050}
\end{Verbatim}

Recursion does take awhile to master, but much of the trouble students have with it in practice
is a consequence of side-effect-full thinking. Nevertheless, you can replace this with a more
imperative (von Neumann) style. See our loops section.


\subsection{Some CS1 Friendly Examples}
\label{cs1:some-cs1-friendly-examples}

\subsubsection{GCD}
\label{cs1:gcd}
This is based on a classic algorithm by Euclid and one that is covered in many introductory computer science
courses. (See {\hyperref[cs1:id5]{{[}GCD{]}}} for a more detailed discussion of this method and the ways it has been coded over the
years, especially in imperative programming languages.)

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{def} \PYG{n}{gcd}\PYG{o}{(}\PYG{n}{a} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{b} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{=} \PYG{k}{if} \PYG{o}{(}\PYG{n}{b} \PYG{o}{==} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{n}{a} \PYG{k}{else} \PYG{n}{gcd}\PYG{o}{(}\PYG{n}{b}\PYG{o}{,} \PYG{n}{a} \PYG{o}{\PYGZpc{}} \PYG{n}{b}\PYG{o}{)}
\end{Verbatim}

The Scala version looks a lot like Euclid's definition!


\subsubsection{Factorial}
\label{cs1:factorial}
This is the basic example that comes from {\hyperref[cs1:miscexplorationsscala]{{[}MiscExplorationsScala{]}}},
which also show show to use Scala and functional programming to rework explicitly recursive computations into
non-recursive versions using higher-order functional thinking.

This shows how to explicitly define the \code{fac(n : Int) : Int} function.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{def} \PYG{n}{fac}\PYG{o}{(}\PYG{n}{n} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{k}{if} \PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{l+m+mi}{1} \PYG{k}{else} \PYG{n}{n} \PYG{o}{*} \PYG{n}{fac}\PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}
\end{Verbatim}

This shows how to define a function \emph{object}. It makes use of the literal syntax we introduced earlier,
You read this as ``fac is a function that maps Int into Int and binds the name \code{n} to the \code{Int} parameter.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{val} \PYG{n}{fac}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=\PYGZgt{}} \PYG{n+nc}{Int} \PYG{k}{=} \PYG{n}{n} \PYG{k}{=\PYGZgt{}} \PYG{k}{if} \PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{l+m+mi}{1} \PYG{k}{else} \PYG{n}{n} \PYG{o}{*} \PYG{n}{fac}\PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}
\end{Verbatim}

In many cases, you can write these functions without explcit recursion, simply by taking advantage of Scala's
innate collections:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{def} \PYG{n}{fac}\PYG{o}{(}\PYG{n}{n} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{(}\PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}\PYG{o}{)}\PYG{o}{.}\PYG{n}{foldLeft}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{o}{(}\PYG{n}{l}\PYG{o}{,}\PYG{n}{r}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n}{l} \PYG{o}{*} \PYG{n}{r}\PYG{o}{)}
\end{Verbatim}

Or even more concisely (and cryptically?)

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{def} \PYG{n}{fac}\PYG{o}{(}\PYG{n}{n} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{(}\PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}\PYG{o}{)}\PYG{o}{.}\PYG{n}{foldLeft}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{k}{\PYGZus{}} \PYG{o}{*} \PYG{k}{\PYGZus{}}\PYG{o}{)}
\end{Verbatim}

We'll look more at higher-order thinking shortly. Many who think of functional programming (especially the 1960's
and 1970's style) tend to think Lisp, which very much required you to think \emph{recursively} most of the time in
practice. Today, the recursive element is still there, but you'll find that the need to use it explicitly is
not required and can be replaced with higher-order abstractions. In the end, students still need to know about
this technique, if only to understand that certain methods (e.g. folds) often have a recursive nature to them.

In addition to rather outdated notions many tend to have about functional programming when it comes to recursion,
the optimization of recursive calls is achieved through a version of tail-recursion elimination (a.k.a. tail call
optimization). See {\hyperref[cs1:tailcalls]{{[}TailCalls{]}}} for more information.


\subsubsection{Monte Carlo $\pi$ Calculation}
\label{cs1:monte-carlo-calculation}\label{cs1:montecarlopi}
An example that often resonates well with students is the Monte Carlo method,
which uses randomness to perform the $\pi$ computation. In the interests
of showing how Scala's approach to functional programming follows the textual
description, we will write the steps and show the code (in Scala) to perform
each step in an integrated fashion.

In the Monte Carlo method for calculating $\pi$, we will randomly
generate a given number of darts using a Scala stream. We \emph{fire} the darts
into a unit circle, which is bounded by a square, whose dimensions are
$2 \times 2$ units.  The darts that fall within the unit circle satisfy the
constraint $x^2 + y^2 \leq 1$.

Let's start by establishing the needed functions. First, here is the now-
familiar \code{square(x:Double)} function, again for reference.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{def} \PYG{n}{sqr}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{)} \PYG{k}{=} \PYG{n}{x} \PYG{o}{*} \PYG{n}{x}
\end{Verbatim}

We use this function to create another function, which tests whether a given
dart, specified as an (x, y) coordinate pair (a Scala tuple), falls within the
unit circle:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{k}{val} \PYG{n}{inCircle}\PYG{k}{:} \PYG{o}{(}\PYG{o}{(}\PYG{k+kt}{Double}\PYG{o}{,} \PYG{k+kt}{Double}\PYG{o}{)}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n+nc}{Boolean} \PYG{k}{=} \PYG{o}{\PYGZob{}} \PYG{k}{case} \PYG{o}{(}\PYG{n}{x}\PYG{o}{,} \PYG{n}{y}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n}{sqr}\PYG{o}{(}\PYG{n}{x}\PYG{o}{)} \PYG{o}{+} \PYG{n}{sqr}\PYG{o}{(}\PYG{n}{y}\PYG{o}{)} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mf}{1.0} \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Let's to a quick sanity check here:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{inCircle}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res1}\PYG{k}{:} \PYG{k+kt}{Boolean} \PYG{o}{=} \PYG{k+kc}{true}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{inCircle}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res2}\PYG{k}{:} \PYG{k+kt}{Boolean} \PYG{o}{=} \PYG{k+kc}{false}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{inCircle}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.7}\PYG{o}{,} \PYG{l+m+mf}{0.7}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res3}\PYG{k}{:} \PYG{k+kt}{Boolean} \PYG{o}{=} \PYG{k+kc}{true}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{inCircle}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.7}\PYG{o}{,} \PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.7}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res4}\PYG{k}{:} \PYG{k+kt}{Boolean} \PYG{o}{=} \PYG{k+kc}{true}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{inCircle}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}
\PYG{n}{res5}\PYG{k}{:} \PYG{k+kt}{Boolean} \PYG{o}{=} \PYG{k+kc}{false}
\end{Verbatim}

So how do we generate a set of darts and test whether they fall within the
circle? We start by using a Scala Stream (more on this in collections).

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{randomPairs} \PYG{k}{=} \PYG{n+nc}{Stream} \PYG{n}{continually} \PYG{o}{(}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{,} \PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{)}
\PYG{n}{randomPairs}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.Stream}\PYG{o}{[}\PYG{o}{(}\PYG{k+kt}{Double}, \PYG{k+kt}{Double}\PYG{o}{)}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Stream}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.45422625790687077}\PYG{o}{,}\PYG{l+m+mf}{0.1916739269602844}\PYG{o}{)}\PYG{o}{,} \PYG{o}{?}\PYG{o}{)}
\end{Verbatim}

\begin{notice}{note}{Note:}
The examples we are showing here, much like typical introductory examples, trade good
pedagogy (not bogging down students with too many details) for performance and scalability.
If you need to operate on a larger number of darts, you'll want to take advantage of \code{StreamIterator}, not \code{Stream}. A StreamIterator can be obtained from a Stream by reworking the code above as
follows:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{randomPairs} \PYG{k}{=} \PYG{n+nc}{Stream} \PYG{n}{continually} \PYG{o}{(}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{,} \PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{)} \PYG{n}{iterator}
\PYG{n}{randomPairs}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.Stream}\PYG{o}{[}\PYG{o}{(}\PYG{k+kt}{Double}, \PYG{k+kt}{Double}\PYG{o}{)}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Stream}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.45422625790687077}\PYG{o}{,}\PYG{l+m+mf}{0.1916739269602844}\PYG{o}{)}\PYG{o}{,} \PYG{o}{?}\PYG{o}{)}
\end{Verbatim}

Notice that the \code{iterator()} method is being invoked. This can be taught after students have learned
more about Scala collections.
\end{notice}

What you see here is the first item of the stream being displayed. The ''?''
indicates that there are more values (an infinite number, in theory) which
will be obtained on demand. This principle is an advanced one but one that is
teachable and can be understood in greater detail later.

So how do we get a finite number of darts? This is where a number of famous
methods from functional programming come to play. One is known as \code{take(n)},
which can take however many we want. Let's use this to show how to print the
first 5 random coordinate pairs.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{randomPairs}\PYG{o}{.}\PYG{n}{take}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}
\PYG{n}{res7}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.Stream}\PYG{o}{[}\PYG{o}{(}\PYG{k+kt}{Double}, \PYG{k+kt}{Double}\PYG{o}{)}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Stream}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.45422625790687077}\PYG{o}{,}\PYG{l+m+mf}{0.1916739269602844}\PYG{o}{)}\PYG{o}{,} \PYG{o}{?}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{randomPairs}\PYG{o}{.}\PYG{n}{take}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}\PYG{o}{.}\PYG{n}{foreach}\PYG{o}{(}\PYG{n}{println}\PYG{o}{)}
\PYG{o}{(}\PYG{l+m+mf}{0.45422625790687077}\PYG{o}{,}\PYG{l+m+mf}{0.1916739269602844}\PYG{o}{)}
\PYG{o}{(}\PYG{l+m+mf}{0.9252028282996272}\PYG{o}{,}\PYG{l+m+mf}{0.5638265909110913}\PYG{o}{)}
\PYG{o}{(}\PYG{l+m+mf}{0.5588908846857542}\PYG{o}{,}\PYG{l+m+mf}{0.21516929857230815}\PYG{o}{)}
\PYG{o}{(}\PYG{l+m+mf}{0.5842149396390998}\PYG{o}{,}\PYG{l+m+mf}{0.7226255374753748}\PYG{o}{)}
\PYG{o}{(}\PYG{l+m+mf}{0.8454163994561401}\PYG{o}{,}\PYG{l+m+mf}{0.6805038035803781}\PYG{o}{)}
\end{Verbatim}

So what is going on here? We're taking the first 5 coordinate pairs in the
stream and applying the \code{println()} function to each item in the stream
(that is, each coordinate pair). While there are some aspects of this that are
advanced, there are some aspects that are \emph{vastly simpler} than their
equivalent in tradition imperative object-oriented languages (e.g. C++, Java,
C\#). For example, we rely on the notion of a tuple (a pair of Double values),
which usually requires the premature exploration of a Pair class in other
languages. Before long, you need to learn a lot of arcane type theory to
understand Pair, whereas in Scala, the type information is \emph{inferred}.

Looking more closely:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{o}{(}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{,} \PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{)}
\PYG{n}{res10}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Double}\PYG{o}{,} \PYG{k+kt}{Double}\PYG{o}{)} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mf}{0.20679803333001656}\PYG{o}{,}\PYG{l+m+mf}{0.91233235776938}\PYG{o}{)}
\end{Verbatim}

This generates a random pair, and it even \emph{looks} like a random pair from mathematics. Of course, it's also type-safe!

So we're now near the point where we can put all of the pieces together. We have a function to determine whether a randomly generated coordinate pair falls within the unit circle. Let's compute $\pi$.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{n} \PYG{k}{=} \PYG{l+m+mi}{1000000}
\PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{1000000}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{darts} \PYG{k}{=} \PYG{n}{randomPairs}\PYG{o}{.}\PYG{n}{take}\PYG{o}{(}\PYG{n}{n}\PYG{o}{)}
\PYG{n}{darts}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.Stream}\PYG{o}{[}\PYG{o}{(}\PYG{k+kt}{Double}, \PYG{k+kt}{Double}\PYG{o}{)}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Stream}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.45422625790687077}\PYG{o}{,}\PYG{l+m+mf}{0.1916739269602844}\PYG{o}{)}\PYG{o}{,} \PYG{o}{?}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{dartsInCircle} \PYG{k}{=} \PYG{n}{darts}\PYG{o}{.}\PYG{n}{count}\PYG{o}{(}\PYG{n}{inCircle}\PYG{o}{)}
\PYG{n}{dartsInCircle}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{784894}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{totalDarts} \PYG{k}{=} \PYG{n}{darts}\PYG{o}{.}\PYG{n}{length}
\PYG{n}{totalDarts}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{1000000}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{area} \PYG{k}{=} \PYG{l+m+mf}{4.0} \PYG{o}{*} \PYG{n}{dartsInCircle} \PYG{o}{/} \PYG{n}{totalDarts}
\PYG{n}{area}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{l+m+mf}{3.139576}
\end{Verbatim}

This is a good time to introduce the \emph{dot-less} syntax, which is often associated with object-oriented programming but actually precedes these languages (C \emph{struct} et al).

You can also write the above code (where you see dots) as follows:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{darts} \PYG{k}{=} \PYG{n}{randomPairs} \PYG{n}{take} \PYG{n}{n}
\PYG{n}{darts}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.Stream}\PYG{o}{[}\PYG{o}{(}\PYG{k+kt}{Double}, \PYG{k+kt}{Double}\PYG{o}{)}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Stream}\PYG{o}{(}\PYG{o}{(}\PYG{l+m+mf}{0.45422625790687077}\PYG{o}{,}\PYG{l+m+mf}{0.1916739269602844}\PYG{o}{)}\PYG{o}{,} \PYG{o}{?}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{dartsInCircle} \PYG{k}{=} \PYG{n}{darts} \PYG{n}{count} \PYG{n}{inCircle}
\PYG{n}{dartsInCircle}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{784894}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{totalDarts} \PYG{k}{=} \PYG{n}{darts} \PYG{n}{length}
\PYG{n}{totalDarts}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{1000000}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{area} \PYG{k}{=} \PYG{l+m+mf}{4.0} \PYG{o}{*} \PYG{n}{dartsInCircle} \PYG{o}{/} \PYG{n}{totalDarts}
\PYG{n}{area}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{l+m+mf}{3.139576}
\end{Verbatim}

At some point, you realize that you want to enter the code into a text editor that can be loaded into
the Scala interpreter (as opposed to being entered interactively).

The actual code for this can be found at
\href{https://bitbucket.org/loyolachicagocs\_plsystems/numerical-explorations-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/numerical-explorations-scala}. You can
pull up the Scala worksheet from \code{MonteCarloPiStreamIteratorChunkFree.sc} (by drilling into Source).

Here's the final version of our function to calculate $\pi$.

We also provide a simple \emph{timing} function, that allows us to time a \emph{block}
of Scala statements. We'll not present it in detail now, but this function
could be given to your students with the hope of  sensitizing them to the
notion of \emph{performance}. It also shows the tremendous power available in Scala
to work with a block of Scala code as an object (which can produce a value).

We're going to use this to show how to measure the execution time of our
$\pi$ calculation by  varying the problem size. Here is the fragment of
code that tries different problem sizes up to  $n = 10^k$, where
$k = \lfloor log_{10}(Int.MaxValue) \rfloor$ ($k = \lfloor
log_{10}(2147483647) \rfloor = 9$)

\begin{notice}{note}{Note:}
You might wonder why we are limited to \code{Int} in this version as opposed
to a 64-bit \code{Int}. It is a perfectly valid idea to ponder, especially in
the modern era. Scala collections do not support operations like \code{take()}
and \code{drop()} with 64-bit Int values. The  explanation for this is a bit
beyond the scope here, but we have worked out 64-bit versions where we
perform the Monte Carlo $\pi$ calculation in chunks. You can visit our
repository for these versions, which are a bit complex compared to the Int
version. We hope future versions of Scala will evolve beyond 32-bit
thinking but don't see this as a show stopper for  introductory teaching.
(We also hope the friendly competition between F\# and Scala, where F\#
supports Int64, will eventually make its way to Scala.
\end{notice}

Here is the output (some output has been deleted for conciseness).

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} :load MonteCarloPiStreamIteratorChunkFree.sc
Loading MonteCarloPiStreamIteratorChunkFree.sc...
sqr: (x: Double)Double
inCircle: ((Double, Double)) =\textgreater{} Boolean = \textless{}function1\textgreater{}
randomPairs: Iterator[(Double, Double)] = non-empty iterator
n: Int = 1000000
darts: Iterator[(Double, Double)] = non-empty iterator
dartsInCircle: Int = 785719
totalDarts: Int = 0
area: Double = Infinity
longDartsInCircle: (numDarts: Int)Long
monteCarloCircleArea: (numDarts: Int)Double
time: [R](block: =\textgreater{} R)R
powers: scala.collection.immutable.Range.Inclusive =
   Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
sizes: scala.collection.immutable.IndexedSeq[Int] =
   Vector(10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000)
problemSizes: scala.collection.immutable.IndexedSeq[Int] =
   Vector(1000000, 10000000, 100000000, 1000000000)
Trying these probem sizes
1000000
10000000
100000000
1000000000
numDarts: 1000000
Elapsed time: 0.149393s
The area is 3.141644
numDarts: 10000000
Elapsed time: 1.110151s
The area is 3.1406688
numDarts: 100000000
Elapsed time: 10.744608s
The area is 3.141555
numDarts: 1000000000
\end{Verbatim}

We will discuss performance and timing issues again when speaking to parallel computing in
{\hyperref[parallel::doc]{\emph{Basic Parallelism using Par}}}.


\subsection{More Scala}
\label{cs1:more-scala}

\subsubsection{While Loop}
\label{cs1:while-loop}\begin{itemize}
\item {} 
While loop

\item {} 
Not an expression

\end{itemize}

In Scala, you can do imperative style loops and interactive loops:

Consider this interactive session to compute well-known example for sum

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{sum}\PYG{o}{(}\PYG{n}{n} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}   \PYG{k}{var} \PYG{n}{i} \PYG{k}{=} \PYG{l+m+mi}{0}
     \PYG{o}{\textbar{}}   \PYG{k}{var} \PYG{n}{sum} \PYG{k}{=} \PYG{l+m+mi}{0}
     \PYG{o}{\textbar{}}   \PYG{k}{while} \PYG{o}{(}\PYG{n}{i} \PYG{o}{\PYGZlt{}=} \PYG{n}{n}\PYG{o}{)} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}     \PYG{n}{sum} \PYG{k}{=} \PYG{n}{sum} \PYG{o}{+} \PYG{n}{n}
     \PYG{o}{\textbar{}}     \PYG{n}{i} \PYG{k}{=} \PYG{n}{i} \PYG{o}{+} \PYG{l+m+mi}{1}
     \PYG{o}{\textbar{}}   \PYG{o}{\PYGZcb{}}
     \PYG{o}{\textbar{}}   \PYG{n}{sum}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}
\PYG{n}{sum}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{n}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{Int}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{100}\PYG{o}{)}
\PYG{n}{res5}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{10100}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{sum}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}
\PYG{n}{res6}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}
\end{Verbatim}

Much is possible without iteration with the added advantage of being recursive and side-effect
free underneath the hood.
\begin{quote}

scala\textgreater{} def sum(n : Int) = (1 to n).sum
sum: (n: Int)Int

scala\textgreater{} sum(0)
res8: Int = 0

scala\textgreater{} sum(100)
res9: Int = 5050
\end{quote}

What about interactive loops?

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{reader} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{ConsoleReader}
\PYG{n}{reader}\PYG{k}{:} \PYG{k+kt}{scala}\PYG{k+kt}{.}\PYG{k+kt}{tools}\PYG{k+kt}{.}\PYG{k+kt}{jline}\PYG{k+kt}{.}\PYG{k+kt}{console}\PYG{k+kt}{.}\PYG{k+kt}{ConsoleReader} \PYG{o}{=}
   \PYG{n}{scala}\PYG{o}{.}\PYG{n}{tools}\PYG{o}{.}\PYG{n}{jline}\PYG{o}{.}\PYG{n}{console}\PYG{o}{.}\PYG{n+nc}{ConsoleReader}\PYG{k}{@}\PYG{l+m+mi}{26075}\PYG{n}{b18}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{var} \PYG{n}{response} \PYG{k}{=} \PYG{l+m+mi}{0}
\PYG{n}{response}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{while} \PYG{o}{(}\PYG{n}{response} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{0} \PYG{o}{\textbar{}\textbar{}} \PYG{n}{response} \PYG{o}{\PYGZgt{}} \PYG{l+m+mi}{100}\PYG{o}{)} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}    \PYG{n}{response} \PYG{k}{=} \PYG{n}{reader}\PYG{o}{.}\PYG{n}{readLine}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Enter a number \PYGZgt{}= 0  and \PYGZlt{}= 100? \PYGZdq{}}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toInt}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{var} \PYG{n}{response} \PYG{k}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}
\PYG{n}{response}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{while} \PYG{o}{(}\PYG{n}{response} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{0} \PYG{o}{\textbar{}\textbar{}} \PYG{n}{response} \PYG{o}{\PYGZgt{}} \PYG{l+m+mi}{100}\PYG{o}{)} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}    \PYG{n}{response} \PYG{k}{=} \PYG{n}{reader}\PYG{o}{.}\PYG{n}{readLine}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Enter a number \PYGZgt{}= 0  and \PYGZlt{}= 100? \PYGZdq{}}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toInt}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}
\PYG{n+nc}{Enter} \PYG{n}{a} \PYG{n}{number} \PYG{o}{\PYGZgt{}=} \PYG{l+m+mi}{0}  \PYG{n}{and} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{100}\PYG{o}{?} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{5}
\PYG{n+nc}{Enter} \PYG{n}{a} \PYG{n}{number} \PYG{o}{\PYGZgt{}=} \PYG{l+m+mi}{0}  \PYG{n}{and} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{100}\PYG{o}{?} \PYG{l+m+mi}{105}
\PYG{n+nc}{Enter} \PYG{n}{a} \PYG{n}{number} \PYG{o}{\PYGZgt{}=} \PYG{l+m+mi}{0}  \PYG{n}{and} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{100}\PYG{o}{?} \PYG{l+m+mi}{100}
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{o}{.}\PYG{o}{.}\PYG{o}{.}
\end{Verbatim}

It is interesting to think about whether we can turn an interactive while loop into one without
side effects. There are so many bad things that happen to us as CS1 educators when we work with
interactive loops:
\begin{itemize}
\item {} 
Improper initialization of the \code{response} variable.

\item {} 
Improper setting of \code{response} upon termination.

\item {} 
etc.

\end{itemize}

This is my early attempt to figure out how to have a side-effect free
interactive while loop. Basic idea:
\begin{itemize}
\item {} 
Use \code{Stream.continually} to get a continuous stream of input lines
read.

\item {} 
Because \code{Stream} is lazy only in the tail, assume a blank line as
the first value of the stream (which is safely ignored). I'd like to
figure out the right way to eliminate this without introducing complexity.

\item {} 
Use \code{takeWhile} to accept input until an appropriate terminating condition (the word ``no'' is entered)

\item {} 
Convert each line to integer, if possible. We simplify exception
management by applying a \code{Try} wrapper to each attempted
conversion. \code{Try} is an important Scala idiom for representing a
computation that either succeeds with a result value or fails with
an exception.

\item {} 
Use \code{flatMap} to get only the input values where the conversion
succeeded. In the process of applying \code{flatMap}, however, we need
to convert each \code{Try} value to an \code{Option} value. \code{Option} is
very similar to \code{Try} but simpler in that it represents all failures as
\code{None}, which \code{flatMap} discards from the resulting list.

\end{itemize}

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} val s1 = "" \#:: Stream.continually(reader.readLine("Prompt: "))
s1: scala.collection.immutable.Stream[String] = Stream(, ?)

scala\textgreater{} val s = s1.takeWhile(\_ != "no")
s: scala.collection.immutable.Stream[String] = Stream(, ?)

scala\textgreater{} val l = s.toList
Prompt: 25
Prompt: 35
Prompt: 55
Prompt:
Prompt: s
Prompt: no
l: List[String] = List("", 25, 35, 55, "", s)

scala\textgreater{} import scala.util.Try
import scala.util.Try

scala\textgreater{} def toInteger(s: String) = Try(s.toInt)
toInteger: (s: String)scala.util.Try[Int]

scala\textgreater{} l.map(toInteger)
res3: List[scala.util.Try[Int]] = List(Failure(java.lang.NumberFormatException: For input string: ""), Success(25), Success(35), Success(55), Failure(java.lang.NumberFormatException: For input string: ""), Failure(java.lang.NumberFormatException: For input string: "s"))

scala\textgreater{} l.map(t =\textgreater{} toInteger(t).toOption)
res6: List[Option[Int]] = List(None, Some(25), Some(35), Some(55), None, None)

scala\textgreater{} l.flatMap(t =\textgreater{} toInteger(t).toOption)
res7: List[Int] = List(25, 35, 55)

scala\textgreater{} l.flatMap(t =\textgreater{} toInteger(t).toOption).sum
res8: Int = 115
\end{Verbatim}


\subsubsection{for loop}
\label{cs1:for-loop}
Similar to the while loop, a for loop exists for \emph{imperative} style
programming, often when there is a need to do something where a
side-effect is needed.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{var} \PYG{n}{sum} \PYG{k}{=} \PYG{l+m+mi}{0}
\PYG{n}{sum}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{0}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{var} \PYG{n}{n} \PYG{k}{=} \PYG{l+m+mi}{100}
\PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{100}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}\PYG{o}{)}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZob{}}
     \PYG{o}{\textbar{}}    \PYG{n}{sum} \PYG{k}{=} \PYG{n}{sum} \PYG{o}{+} \PYG{n}{i}
     \PYG{o}{\textbar{}} \PYG{o}{\PYGZcb{}}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}The sum is \PYGZdl{}sum\PYGZdq{}}\PYG{o}{)}
\PYG{n+nc}{The} \PYG{n}{sum} \PYG{n}{is} \PYG{l+m+mi}{5050}
\end{Verbatim}


\subsubsection{for comprehension}
\label{cs1:for-comprehension}
A for comprehension is designed for where you want a more functional style. That is, there is no intention
of having side effects, and it is likely that you want to use the result of the comprehension in another
computation.

Let's look at something a bit more interesting: Getting the first \code{n} squares:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{n} \PYG{k}{=} \PYG{l+m+mi}{10}
\PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{10}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{first\PYGZus{}n\PYGZus{}squares} \PYG{k}{=} \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}\PYG{o}{)} \PYG{k}{yield} \PYG{o}{\PYGZob{}} \PYG{n}{i} \PYG{o}{*} \PYG{n}{i} \PYG{o}{\PYGZcb{}}
\PYG{n}{first\PYGZus{}n\PYGZus{}squares}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Vector}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{l+m+mi}{36}\PYG{o}{,} \PYG{l+m+mi}{49}\PYG{o}{,} \PYG{l+m+mi}{64}\PYG{o}{,} \PYG{l+m+mi}{81}\PYG{o}{,} \PYG{l+m+mi}{100}\PYG{o}{)}
\end{Verbatim}

You could wrap this up nicely in a Scala function as follows:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{def} \PYG{n}{squares}\PYG{o}{(}\PYG{n}{n} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{=} \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}\PYG{o}{)} \PYG{k}{yield} \PYG{o}{\PYGZob{}} \PYG{n}{i} \PYG{o}{*} \PYG{n}{i} \PYG{o}{\PYGZcb{}}
\PYG{n}{squares}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{n}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{squares}\PYG{o}{(}\PYG{l+m+mi}{10}\PYG{o}{)}
\PYG{n}{res7}\PYG{k}{:} \PYG{k+kt}{scala.collection.immutable.IndexedSeq}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=}
   \PYG{n+nc}{Vector}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{16}\PYG{o}{,} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{l+m+mi}{36}\PYG{o}{,} \PYG{l+m+mi}{49}\PYG{o}{,} \PYG{l+m+mi}{64}\PYG{o}{,} \PYG{l+m+mi}{81}\PYG{o}{,} \PYG{l+m+mi}{100}\PYG{o}{)}
\end{Verbatim}


\subsubsection{options and failure sans exceptions}
\label{cs1:options-and-failure-sans-exceptions}
Per the Scala documentation: An option represents optional values. Instances
of Option are either an instance of scala.Some or the object None.

The Scala Option type is useful for dealing with the notion of success and
failure (but is not limited to supporting this concept). In the interests of
keeping this discussion focused on being CS1-friendly, an Option is always
connected to an underlying type. For example Option{[}Int{]} means that you either
get the Int, or nothing (None).

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{i} \PYG{k}{=} \PYG{n+nc}{Some}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}
\PYG{n}{i}\PYG{k}{:} \PYG{k+kt}{Some}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Some}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{j} \PYG{k}{=} \PYG{n+nc}{None}
\PYG{n}{j}\PYG{k}{:} \PYG{k+kt}{None}\PYG{k+kt}{.}\PYG{k}{type} \PYG{o}{=} \PYG{n+nc}{None}
\end{Verbatim}

\code{Some} and \code{None} are both \emph{case classes} that extend \code{Option{[}A{]}} (a generic class that allows you
to use any time). While knowing all of the details requires a mastery of object-oriented programming (and
perhaps more), the introduction of this idea is remarkably straightforward and one that can help students
to write better code from the beginning. In CS1 courses, we tend to spend a lot of time handling special
cases, and options give us a framework for dealing with missing information, etc.

As you can see from the above, \code{i} is defined as some value, in this case 3. It's a wrapped value, of course,
that must be unbundled later. For example, here is an attempt to use the value \code{i} (incorrectly):

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} i + 5
\textless{}console\textgreater{}:9: error: type mismatch;
 found   : Int(5)
 required: String
              i + 5
                  \textasciicircum{}
\end{Verbatim}

So how do we make use of \code{i} and \code{j}? A method associated with options, \code{getOrElse} allows us to get the
\emph{option}, if set to \emph{some} value. Rather delightfully, we can set a value to be used, if the option was not set
previously.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{i} \PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{res13}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{3}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{j} \PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{res14}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}
\end{Verbatim}

So now if we want to use this value in a computation, we can just do this:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{i}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)} \PYG{o}{+} \PYG{n}{j}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{res17}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{2}
\end{Verbatim}

Options have their uses throughout Scala, notably its libraries. For example, maps (a.k.a. associative
structures/arrays) use option to return the result of getting a key from the map:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{map} \PYG{k}{=} \PYG{n}{scala}\PYG{o}{.}\PYG{n}{collection}\PYG{o}{.}\PYG{n}{mutable}\PYG{o}{.}\PYG{n+nc}{HashMap}\PYG{o}{.}\PYG{n}{empty}\PYG{o}{[}\PYG{k+kt}{String}, \PYG{k+kt}{Int}\PYG{o}{]}
\PYG{n}{map}\PYG{k}{:} \PYG{k+kt}{scala.collection.mutable.HashMap}\PYG{o}{[}\PYG{k+kt}{String},\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Map}\PYG{o}{(}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map} \PYG{o}{+=} \PYG{o}{(}\PYG{l+s}{\PYGZdq{}scala\PYGZdq{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{10}\PYG{o}{)}
\PYG{n}{res4}\PYG{k}{:} \PYG{k+kt}{map}\PYG{k+kt}{.}\PYG{k}{type} \PYG{o}{=} \PYG{n+nc}{Map}\PYG{o}{(}\PYG{n}{scala} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{10}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map} \PYG{o}{+=} \PYG{o}{(}\PYG{l+s}{\PYGZdq{}java\PYGZdq{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{20}\PYG{o}{)}
\PYG{n}{res5}\PYG{k}{:} \PYG{k+kt}{map}\PYG{k+kt}{.}\PYG{k}{type} \PYG{o}{=} \PYG{n+nc}{Map}\PYG{o}{(}\PYG{n}{scala} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{n}{java} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{20}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map} \PYG{o}{+=} \PYG{o}{(}\PYG{l+s}{\PYGZdq{}C\PYGZsh{}\PYGZdq{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{15}\PYG{o}{)}
\PYG{n}{res6}\PYG{k}{:} \PYG{k+kt}{map}\PYG{k+kt}{.}\PYG{k}{type} \PYG{o}{=} \PYG{n+nc}{Map}\PYG{o}{(}\PYG{n}{scala} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{n}{java} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{20}\PYG{o}{,} \PYG{n}{C}\PYG{k}{\PYGZsh{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{15}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map} \PYG{o}{+=} \PYG{o}{(}\PYG{l+s}{\PYGZdq{}F\PYGZsh{}\PYGZdq{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{25}\PYG{o}{)}
\PYG{n}{res7}\PYG{k}{:} \PYG{k+kt}{map}\PYG{k+kt}{.}\PYG{k}{type} \PYG{o}{=} \PYG{n+nc}{Map}\PYG{o}{(}\PYG{n}{scala} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{n}{F}\PYG{k}{\PYGZsh{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{n}{java} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{20}\PYG{o}{,} \PYG{n}{C}\PYG{k}{\PYGZsh{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{15}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map} \PYG{o}{+=} \PYG{o}{(}\PYG{l+s}{\PYGZdq{}scala\PYGZdq{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{22}\PYG{o}{)}
\PYG{n}{res8}\PYG{k}{:} \PYG{k+kt}{map}\PYG{k+kt}{.}\PYG{k}{type} \PYG{o}{=} \PYG{n+nc}{Map}\PYG{o}{(}\PYG{n}{scala} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{22}\PYG{o}{,} \PYG{n}{F}\PYG{k}{\PYGZsh{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{25}\PYG{o}{,} \PYG{n}{java} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{20}\PYG{o}{,} \PYG{n}{C}\PYG{k}{\PYGZsh{}} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{l+m+mi}{15}\PYG{o}{)}
\end{Verbatim}

Here's an attempt to get the case-sensitive and case-insensitive versions of key, F\#, from the map:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}F\PYGZsh{}\PYGZdq{}}\PYG{o}{)}
\PYG{n}{res9}\PYG{k}{:} \PYG{k+kt}{Option}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Some}\PYG{o}{(}\PYG{l+m+mi}{25}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{map}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}f\PYGZsh{}\PYGZdq{}}\PYG{o}{)}
\PYG{n}{res10}\PYG{k}{:} \PYG{k+kt}{Option}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{None}
\end{Verbatim}

Seasoned Java programmers know that an entry not found in the map will result in the \emph{null} value being
returned. This differs from Scala, because the value gotten from the map must be \emph{tested} before attempting
to use it in any way.

In Scala, because \code{None} and \code{Some(25)} are both options, you can use \code{getOrElse} to obtain the
options value (irrespective of whether the value is null, or not set) without writing an (unwanted) if-then-else
statement, which results in bloat (in most programming languages).

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{entry} \PYG{k}{=} \PYG{n}{map}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}F\PYGZsh{}\PYGZdq{}}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{entry}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{25}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}The entry for F\PYGZsh{} is \PYGZdl{}entry\PYGZdq{}}\PYG{o}{)}
\PYG{n+nc}{The} \PYG{n}{entry} \PYG{k}{for} \PYG{n}{F}\PYG{k}{\PYGZsh{}} \PYG{n}{is} \PYG{l+m+mi}{25}
\end{Verbatim}

It's often the case that we have \emph{default} values associated with failure to
accomplish a certain task. The Option idiom is an attempt to standardize this
for core data structures and (as we'll see) other situations (e.g. working
with complex for comprehensions). In the case of maps, an entry not found
would usually default to 0 or -1 (a convention that dates back to the earliest
days of C), which is preferable to throwing exceptions for no good reason (not to
mention our general dislike of prematurely covering exceptions as a programming
technique in CS1 in particular.)


\subsubsection{yield}
\label{cs1:yield}
Yield is used to take a collection and produce a new one with mapped values.

Let's produce a List{[}Int{]} of squares from a List{[}Int{]} of the first three
integers:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{l} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}
\PYG{n}{l}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{l}
\PYG{n}{res10}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{n}{l}\PYG{o}{)} \PYG{k}{yield} \PYG{o}{\PYGZob{}} \PYG{n}{i} \PYG{o}{*} \PYG{n}{i} \PYG{o}{\PYGZcb{}}
\PYG{n}{res11}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{)}
\end{Verbatim}

Let's try this with an Array{[}Int{]}:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{val} \PYG{n}{a} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}
\PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{n}{a}\PYG{o}{)} \PYG{k}{yield} \PYG{n}{i} \PYG{o}{*} \PYG{n}{i}
\PYG{n}{res16}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{)}
\end{Verbatim}

For the most part, when iterating over values and using yield, you will always get
back the same type, or another type that makes sense.

In these basic examples, the above can also be written as follows (without the for):

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{l} \PYG{n}{map} \PYG{o}{(}\PYG{n}{i} \PYG{k}{=\PYGZgt{}} \PYG{n}{i} \PYG{o}{*} \PYG{n}{i}\PYG{o}{)}
\PYG{n}{res17}\PYG{k}{:} \PYG{k+kt}{List}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{)}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{a} \PYG{n}{map} \PYG{o}{(}\PYG{n}{i} \PYG{k}{=\PYGZgt{}} \PYG{n}{i} \PYG{o}{*} \PYG{n}{i}\PYG{o}{)}
\PYG{n}{res18}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{Int}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Array}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{)}
\end{Verbatim}


\subsubsection{Ranges}
\label{cs1:ranges}
Ranges should be familiar to you if you've worked with other agile scripting languages, e.g. Python.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{)}
\PYG{n}{res20}\PYG{k}{:} \PYG{k+kt}{scala}\PYG{k+kt}{.}\PYG{k+kt}{collection}\PYG{k+kt}{.}\PYG{k+kt}{immutable}\PYG{k+kt}{.}\PYG{k+kt}{Range} \PYG{o}{=} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{4}\PYG{o}{)}
\end{Verbatim}

This gives a range of values from 1 to 5 but stopping at the last value before 5. The increment
is +1.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{2}\PYG{o}{)}
\PYG{n}{res22}\PYG{k}{:} \PYG{k+kt}{scala}\PYG{k+kt}{.}\PYG{k+kt}{collection}\PYG{k+kt}{.}\PYG{k+kt}{immutable}\PYG{k+kt}{.}\PYG{k+kt}{Range} \PYG{o}{=} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{,} \PYG{l+m+mi}{7}\PYG{o}{)}
\end{Verbatim}

You can also work backwards:

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{,} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{)}
\PYG{n}{res24}\PYG{k}{:} \PYG{k+kt}{scala}\PYG{k+kt}{.}\PYG{k+kt}{collection}\PYG{k+kt}{.}\PYG{k+kt}{immutable}\PYG{k+kt}{.}\PYG{k+kt}{Range} \PYG{o}{=} \PYG{n+nc}{Range}\PYG{o}{(}\PYG{l+m+mi}{9}\PYG{o}{,} \PYG{l+m+mi}{7}\PYG{o}{,} \PYG{l+m+mi}{5}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{)}
\end{Verbatim}


\subsubsection{Multiple generators}
\label{cs1:multiple-generators}

\subsubsection{If guards}
\label{cs1:if-guards}

\subsubsection{Variables}
\label{cs1:variables}

\subsubsection{Patterns}
\label{cs1:patterns}

\subsection{Files}
\label{cs1:files}\begin{itemize}
\item {} 
Can use Scanner

\item {} 
scala.io.Source

\item {} 
Scala Iterator{[}Char{]}

\item {} 
getLines : Iterator{[}String{]}

\item {} 
Use with higher-order methods

\item {} 
Write with PrintWriter

\item {} 
Introduce APIs?

\end{itemize}


\subsection{Classes and Objects}
\label{cs1:classes-and-objects}

\subsubsection{Classes}
\label{cs1:classes}
Here is the familiar Point class. It's often shown where the (x, y) coordinate pair are Int (even in
the Scala documentation) but is even more interesting with Double. This is an elaborated version that
includes elements appropriate mostly to CS1 and some that are best covered in CS2 and beyond.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{class} \PYG{n+nc}{Point}\PYG{o}{(}\PYG{n}{initial\PYGZus{}x}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{initial\PYGZus{}y}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{)} \PYG{o}{\PYGZob{}}
   \PYG{k}{var} \PYG{n}{x}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{n}{initial\PYGZus{}x}
   \PYG{k}{var} \PYG{n}{y}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{n}{initial\PYGZus{}y}

   \PYG{k}{def} \PYG{n}{move}\PYG{o}{(}\PYG{n}{dx}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{dy}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{n}{x} \PYG{k}{=} \PYG{n}{x} \PYG{o}{+} \PYG{n}{dx}
      \PYG{n}{y} \PYG{k}{=} \PYG{n}{y} \PYG{o}{+} \PYG{n}{dy}
   \PYG{o}{\PYGZcb{}}

   \PYG{k}{def} \PYG{n}{distanceToOrigin}\PYG{o}{(}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{o}{\PYGZob{}}
      \PYG{n}{math}\PYG{o}{.}\PYG{n}{sqrt}\PYG{o}{(}\PYG{n}{x} \PYG{o}{*} \PYG{n}{x} \PYG{o}{+} \PYG{n}{y} \PYG{o}{*} \PYG{n}{y}\PYG{o}{)}
   \PYG{o}{\PYGZcb{}}

   \PYG{k}{def} \PYG{n}{distanceTo}\PYG{o}{(}\PYG{n}{p} \PYG{k}{:} \PYG{k+kt}{Point}\PYG{o}{)} \PYG{k}{=} \PYG{o}{\PYGZob{}}
      \PYG{n}{math}\PYG{o}{.}\PYG{n}{sqrt}\PYG{o}{(} \PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{x} \PYG{o}{\PYGZhy{}} \PYG{n}{x}\PYG{o}{)} \PYG{o}{*} \PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{x} \PYG{o}{\PYGZhy{}} \PYG{n}{x}\PYG{o}{)} \PYG{o}{+} \PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{y} \PYG{o}{\PYGZhy{}} \PYG{n}{y}\PYG{o}{)} \PYG{o}{*} \PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{y} \PYG{o}{\PYGZhy{}} \PYG{n}{y}\PYG{o}{)} \PYG{o}{)}
   \PYG{o}{\PYGZcb{}}

   \PYG{k}{def} \PYG{n}{add}\PYG{o}{(}\PYG{n}{p} \PYG{k}{:} \PYG{k+kt}{Point}\PYG{o}{)} \PYG{k}{=} \PYG{o}{\PYGZob{}}
      \PYG{n}{x} \PYG{k}{=} \PYG{n}{x} \PYG{o}{+} \PYG{n}{p}\PYG{o}{.}\PYG{n}{x}
      \PYG{n}{y} \PYG{k}{=} \PYG{n}{y} \PYG{o}{+} \PYG{n}{p}\PYG{o}{.}\PYG{n}{y}
      \PYG{k}{this}
   \PYG{o}{\PYGZcb{}}

   \PYG{k}{def} \PYG{o}{+}\PYG{o}{(}\PYG{n}{p} \PYG{k}{:} \PYG{k+kt}{Point}\PYG{o}{)} \PYG{k}{=} \PYG{o}{\PYGZob{}}
      \PYG{n}{add}\PYG{o}{(}\PYG{n}{p}\PYG{o}{)}
   \PYG{o}{\PYGZcb{}}

   \PYG{k}{override} \PYG{k}{def} \PYG{n}{toString}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{String} \PYG{o}{=} \PYG{n}{s}\PYG{l+s}{\PYGZdq{}(\PYGZdl{}x, \PYGZdl{}y)\PYGZdq{}}\PYG{o}{;}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

What does this class Point show?
\begin{itemize}
\item {} 
how to create a simple Scala class. Notice the complete lack of keyboards and public/private/static that
tend to confuse students!

\item {} 
Scala brings back \emph{disciplined} operator overloading. We'd probably not use this in CS1, but it is entirely
appropriate for CS2.

\item {} 
Shows how to refer to the object (familiarly) with \code{this}. Again, the methods relying on this might be
more appropriate for CS2 or even later courses that dive into OOP's complexity.

\item {} 
Constructors? The Scala class definition itself makes it clear how one constructs an instance. Just like
a function definition in general, there can be default values. It is liberating not to have constructors
(especially too many of them), especially when trying to introduce a topic. (This will become readily
apparent when we look at \emph{case classes}, which provide a mechanism for more data-centric OO abstraction.)

\item {} 
Convert an instance of class Point to a String representation using \code{ToString()}. \code{ToString()} can be
a valuable pedagogical tool, done right (as observed in languages like Python). Scala 2.10 gives us the
ability to do type-safe string interpolation by substituting the value of variables (their String
representation) into a String template. In Scala, prefixing a string literal with \code{s} will give you
a string where any variables (beginning with \code{\$}) are substituted. Here, it allows us to get a beautiful
representation of a point as an (x, y) pair with virtually no effort or complexity!

\end{itemize}

Let's take a look at how the \code{Point} class is used:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{val} \PYG{n}{p} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Point}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}
\PYG{k}{val} \PYG{n}{q} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Point}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}

\PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}Two points \PYGZdl{}p and \PYGZdl{}q\PYGZdq{}}\PYG{o}{)}

\PYG{k}{val} \PYG{n}{distanceToOrigin} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{distanceToOrigin}\PYG{o}{(}\PYG{o}{)}

\PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}distance from p to origin = \PYGZdl{}distanceToOrigin\PYGZdq{}}\PYG{o}{)}

\PYG{k}{val} \PYG{n}{dpq} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{distanceTo}\PYG{o}{(}\PYG{n}{q}\PYG{o}{)}
\PYG{k}{val} \PYG{n}{dqp} \PYG{k}{=} \PYG{n}{q}\PYG{o}{.}\PYG{n}{distanceTo}\PYG{o}{(}\PYG{n}{p}\PYG{o}{)}

\PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}d(p,q) = \PYGZdl{}dpq\PYGZdq{}}\PYG{o}{)}
\PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}d(q,p) = \PYGZdl{}dqp\PYGZdq{}}\PYG{o}{)}

\PYG{k}{val} \PYG{n}{pointSum} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{add}\PYG{o}{(}\PYG{n}{q}\PYG{o}{)}
\PYG{k}{val} \PYG{n}{pointSumOp} \PYG{k}{=} \PYG{n}{p} \PYG{o}{+} \PYG{n}{q}

\PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}p.add(q) = \PYGZdl{}pointSum; p + q = \PYGZdl{}pointSumOp\PYGZdq{}}\PYG{o}{)}
\end{Verbatim}

This results in the following output.

\begin{Verbatim}[commandchars=\\\{\}]
scala\PYGZgt{} :load point.sc
:load point.sc
Loading point.sc...
defined class Point
p: Point = (2.0, 3.0)
q: Point = (\PYGZhy{}2.0, 3.0)
Two points (2.0, 3.0) and (\PYGZhy{}2.0, 3.0)
distanceToOrigin: Double = 3.605551275463989
distance from p to origin = 3.605551275463989
dpq: Double = 4.0
dqp: Double = 4.0
d(p,q) = 4.0
d(q,p) = 4.0
pointSum: Point = (0.0, 6.0)
pointSumOp: Point = (\PYGZhy{}2.0, 9.0)
p.add(q) = (\PYGZhy{}2.0, 9.0); p + q = (\PYGZhy{}2.0, 9.0)
\end{Verbatim}


\subsubsection{A Look at Singleton Objects}
\label{cs1:a-look-at-singleton-objects}
At some point, relying on the interpreter for trying out the Point class (as we have been doing until
now) grows a bit tedious. Furthermore, sometimes you want to have a complete, functioning program that
includes not just the class Point but also a driver program--often found in a \code{main()} method--that
allows you to run it from the command line.

Scala's answer to \code{main()} (largely a vestige of C-based languages) is to support \emph{singleton objects},
which we rely upon in some more advanced examples. While we consider the singleton pattern to be a bit
overrated and overused (e.g. \code{Runtime.getRuntime()} and many others like it in Java's API), the
singleton object as found here is completely decoupled from any class and allows you to create an
\emph{environment} so to speak with its own namespace but without the burden of a full class definition.

In this example, we create a singleton object to act as our \code{main()} driver.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{object} \PYG{n+nc}{PointDemo} \PYG{o}{\PYGZob{}}
   \PYG{k}{def} \PYG{n}{apply}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{val} \PYG{n}{p} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Point}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{q} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Point}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{)}

      \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}Two points \PYGZdl{}p and \PYGZdl{}q\PYGZdq{}}\PYG{o}{)}

      \PYG{k}{val} \PYG{n}{distanceToOrigin} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{distanceToOrigin}\PYG{o}{(}\PYG{o}{)}

      \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}distance from p to origin = \PYGZdl{}distanceToOrigin\PYGZdq{}}\PYG{o}{)}

      \PYG{k}{val} \PYG{n}{dpq} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{distanceTo}\PYG{o}{(}\PYG{n}{q}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{dqp} \PYG{k}{=} \PYG{n}{q}\PYG{o}{.}\PYG{n}{distanceTo}\PYG{o}{(}\PYG{n}{p}\PYG{o}{)}

      \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}d(p,q) = \PYGZdl{}dpq\PYGZdq{}}\PYG{o}{)}
      \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}d(q,p) = \PYGZdl{}dqp\PYGZdq{}}\PYG{o}{)}

      \PYG{k}{val} \PYG{n}{pointSum} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{add}\PYG{o}{(}\PYG{n}{q}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{pointSumOp} \PYG{k}{=} \PYG{n}{p} \PYG{o}{+} \PYG{n}{q}

      \PYG{n}{println}\PYG{o}{(}\PYG{n}{s}\PYG{l+s}{\PYGZdq{}p.add(q) = \PYGZdl{}pointSum; p + q = \PYGZdl{}pointSumOp\PYGZdq{}}\PYG{o}{)}
   \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}

\PYG{n+nc}{PointDemo}\PYG{o}{(}\PYG{o}{)}
\end{Verbatim}

Similar to a class definition, you \emph{can} have methods. Notably absent, however, are any parameters to
the object name. To create an entry point that allows the object to be used like any other Scala function,
we define an \code{apply()} method, which may or may not have parameters. In our case, we just want to be able
to run the same demo code we produced previously and then invoke the PointDemo as a function, e.g.
\code{PointDemo()}. This could be further wrapped with some logic to handle command-line arguments, etc.
More on that towards the end.


\subsection{Useful REPL functionality}
\label{cs1:useful-repl-functionality}
The Scala REPL supports a number of commands that can be greatly helpful for working interactively. We've
relied on many of these in the preparation of this tutorial but will focus on the highlights, especially
for use in CS1 teaching.

\begin{Verbatim}[commandchars=\\\{\}]
scala\PYGZgt{} :help
All commands can be abbreviated, e.g. :he instead of :help.
Those marked with a * have more detailed help, e.g. :help imports.

:cp \PYGZlt{}path\PYGZgt{}                 add a jar or directory to the classpath
:help [command]            print this summary or command\PYGZhy{}specific help
:history [num]             show the history (optional num is commands to show)
:h? \PYGZlt{}string\PYGZgt{}               search the history
:imports [name name ...]   show import history, identifying sources of names
:implicits [\PYGZhy{}v]            show the implicits in scope
:javap \PYGZlt{}path\textbar{}class\PYGZgt{}        disassemble a file or class name
:load \PYGZlt{}path\PYGZgt{}               load and interpret a Scala file
:paste                     enter paste mode: all input up to ctrl\PYGZhy{}D compiled together
:power                     enable power user mode
:quit                      exit the interpreter
:replay                    reset execution and replay all previous commands
:reset                     reset the repl to its initial state, forgetting all session entries
:sh \PYGZlt{}command line\PYGZgt{}         run a shell command (result is implicitly =\PYGZgt{} List[String])
:silent                    disable/enable automatic printing of results
:type [\PYGZhy{}v] \PYGZlt{}expr\PYGZgt{}          display the type of an expression without evaluating it
:warnings                  show the suppressed warnings from the most recent line which had any
\end{Verbatim}


\subsubsection{paste}
\label{cs1:paste}
When writing longer definitions in the REPL, it can be tricky. Having paste mode allows you to take some
code you have (perhaps from an editor where you are typing a Scala program) and copy/paste into the Scala
session.

This shows an example of entering a slightly more verbose than needed definition of the \code{square()}
function (presented earlier in this section):

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{:}\PYG{k+kt}{paste}
\PYG{c+c1}{// Entering paste mode (ctrl\PYGZhy{}D to finish)}

\PYG{k}{def} \PYG{n}{square}\PYG{o}{(}\PYG{n}{x} \PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)} \PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZob{}}
   \PYG{n}{x} \PYG{o}{*} \PYG{n}{x}
\PYG{o}{\PYGZcb{}}

\PYG{c+c1}{// Exiting paste mode, now interpreting.}

\PYG{n}{square}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{x}\PYG{k+kt}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{k+kt}{Int}
\end{Verbatim}

Notice that you don't see the continuation characters when entering multiple lines of text.


\subsubsection{load}
\label{cs1:load}
Many programmers coming to Scala find it a bit frustrating at first that some things (like interactive
scripts, found in languages like Python) don't work quite the same way. More often than not, the real issue
is whether there is an easy way to load a script into the REPL--as opposed to having to run it on the
command line (which is also possible but not the focus of this section). It is a matter of loading
the filename, which may be an absolute or relative path.

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{k}{:}\PYG{k+kt}{load} \PYG{k+kt}{myscript.scala}
\end{Verbatim}


\subsubsection{history}
\label{cs1:history}
History should be familiar to anyone who has used modern Unix shells. Even if you haven't, you've probably
used the history buffer, which allows you to use the up/down arrows or emacs/vi commands (\textasciicircum{}p, \textasciicircum{}n, j, k) to
access previous and next commands in the history buffer.

Scala also allows you to do \textasciicircum{}r to perform a regex search for text within a previous command. We rely on
this heavily in our work, especially in this section, where it was necessary to look up previous attempts
within the REPL so they could be pasted into the notes!

In this example, I used \textasciicircum{}r to search for the substring ``val'' so I could find a previous value definition in
my REPL session:

\begin{Verbatim}[commandchars=\\\{\}]
(reverse-i-search){}`val': val entry = map.get("F\#").getOrElse(-1)
\end{Verbatim}

When you type \textasciicircum{}r, you'll be given the ``(reverse-i-search)'' prompt to perform a search. While the full
functionality of regex is provided, the nominal use is to type a few characters of something you
probably remember (at least partially). More often than not, I am looking for previous ``val'' or ``def''
(functions).


\subsection{Additional Resources}
\label{cs1:additional-resources}

\section{CS2}
\label{cs2::doc}\label{cs2:cs2}
\begin{notice}{warning}{Warning:}
This section is not ready yet. Working on it!
\end{notice}


\subsection{Collections}
\label{cs2:collections}\begin{itemize}
\item {} 
Just for Scala

\item {} 
Doesn't make sense before loops in most languages.

\item {} 
One mutable, one immutable

\item {} 
Many standard methods

\item {} 
Many higher-order methods

\item {} 
Syntax

\item {} 
Use () for indexing

\item {} 
List also have ML style operations

\item {} 
Creation, pass-by-name

\end{itemize}


\subsection{Case Classes}
\label{cs2:case-classes}\begin{itemize}
\item {} 
Immutable struct in simplest usage

\item {} 
Simple syntax for grouping data

\item {} 
Works as a pattern

\item {} 
Copy method

\end{itemize}


\subsection{GUIs}
\label{cs2:guis}\begin{itemize}
\item {} 
scala.swing wraps javax.swing

\item {} 
Cleaner beginner syntax

\item {} 
No explicit inheritance

\item {} 
Reactions use partial functions

\item {} 
Drawbacks: Currently no JTree, Tables complex, Button syntax uses companion object

\item {} 
Full Java2D

\item {} 
Really using Java

\item {} 
Override paint method

\item {} 
Events for animations

\item {} 
Keyboard, Mouse, Timer

\end{itemize}


\subsubsection{Simple GUI Example}
\label{cs2:simple-gui-example}
This example shows a simple GUI where there is no inheritance.
Clicking the button increments the number in the text field. If the user
has changed it so that it is not an integer, it is set back to 0.

Those familiar with Java will notice a lot of similarities. This is because
the scala.swing library is a wrapper around Java's Swing library. The
ideas are similar, but the way in which you interact with them has been
changed to match the Scala style.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{import} \PYG{n+nn}{swing.\PYGZus{}}

\PYG{k}{val} \PYG{n}{frame} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{MainFrame}
\PYG{k}{val} \PYG{n}{field} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{TextField}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}0\PYGZdq{}}\PYG{o}{)}
\PYG{k}{val} \PYG{n}{button} \PYG{k}{=} \PYG{n+nc}{Button}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Increment\PYGZdq{}}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{k}{try} \PYG{o}{\PYGZob{}}
        \PYG{n}{field}\PYG{o}{.}\PYG{n}{text} \PYG{k}{=} \PYG{o}{(}\PYG{n}{field}\PYG{o}{.}\PYG{n}{text}\PYG{o}{.}\PYG{n}{toInt}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toString}
    \PYG{o}{\PYGZcb{}} \PYG{k}{catch} \PYG{o}{\PYGZob{}}
    \PYG{k}{case} \PYG{n}{ex}\PYG{k}{:}
        \PYG{k+kt}{NumberFormatException} \PYG{o}{=\PYGZgt{}} \PYG{n}{field}\PYG{o}{.}\PYG{n}{text} \PYG{k}{=} \PYG{l+s}{\PYGZdq{}0\PYGZdq{}}
    \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}

\PYG{k}{val} \PYG{n}{bp} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{BorderPanel}
\PYG{k}{import} \PYG{n+nn}{BorderPanel.Position.\PYGZus{}}
\PYG{n}{bp}\PYG{o}{.}\PYG{n}{layout} \PYG{o}{+=} \PYG{n}{field} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{North}
\PYG{n}{bp}\PYG{o}{.}\PYG{n}{layout} \PYG{o}{+=} \PYG{n}{button} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{Center}
\PYG{n}{frame}\PYG{o}{.}\PYG{n}{contents} \PYG{k}{=} \PYG{n}{bp}
\PYG{n}{frame}\PYG{o}{.}\PYG{n}{centerOnScreen}
\PYG{n}{frame}\PYG{o}{.}\PYG{n}{open}
\end{Verbatim}


\subsubsection{Simple GUI Example using scala.util.Try}
\label{cs2:simple-gui-example-using-scala-util-try}
Scala supports simplified exception handling through its
\code{scala.util.Try} wrapper type. This is an important Scala idiom for
representing a computation that either succeeds with a result value or
fails with an exception.

For example, say you want to validate and convert a text field in your
UI from string to integer. You could write this simple conversion
function to do so:

\begin{Verbatim}[commandchars=\\\{\}]
scala\textgreater{} def toInteger(s: String) = scala.util.Try(s.toInt)
toInteger: (s: String)scala.util.Try[Int]

res0: scala.util.Try[Int] = Failure(java.lang.NumberFormatException: For input string: "blah")

scala\textgreater{} toInteger("35")
res1: scala.util.Try[Int] = Success(35)
\end{Verbatim}

Then you can use \code{getOrElse} to process the enclosed value and, if
the \code{Try} value represents failure, return the given default value
(as you see above when we tried to validate the string ``blah'').

\begin{Verbatim}[commandchars=\\\{\}]
\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{toInteger}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}35\PYGZdq{}}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{res2}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{l+m+mi}{35}

\PYG{n}{scala}\PYG{o}{\PYGZgt{}} \PYG{n}{toInteger}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}blah\PYGZdq{}}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}
\PYG{n}{res3}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}
\end{Verbatim}

It's clear that being able to validate input efficiently is something
that excites us. It certainly makes UI development more reliable and
resilient to failures. (We've had more than our share of fun chasing
down validation bugs in web and mobile app development. Most of the
time it is caused by unnecessarily complex validation logic.)

You can see how this plays out in a slightly reworked version of the code:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{import} \PYG{n+nn}{swing.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{scala.util.Try}

\PYG{k}{val} \PYG{n}{frame} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{MainFrame}
\PYG{k}{val} \PYG{n}{field} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{TextField}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}0\PYGZdq{}}\PYG{o}{)}

\PYG{k}{val} \PYG{n}{button} \PYG{k}{=} \PYG{n+nc}{Button}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Increment\PYGZdq{}}\PYG{o}{)} \PYG{o}{\PYGZob{}}
  \PYG{k}{val} \PYG{n}{attempt} \PYG{k}{=} \PYG{n+nc}{Try}\PYG{o}{(}\PYG{n}{field}\PYG{o}{.}\PYG{n}{text}\PYG{o}{.}\PYG{n}{toInt}\PYG{o}{)} 
  \PYG{n}{field}\PYG{o}{.}\PYG{n}{text} \PYG{k}{=} \PYG{o}{(}\PYG{n}{attempt}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toString}
\PYG{o}{\PYGZcb{}}

\PYG{k}{val} \PYG{n}{bp} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{BorderPanel}
\PYG{k}{import} \PYG{n+nn}{BorderPanel.Position.\PYGZus{}}
\PYG{n}{bp}\PYG{o}{.}\PYG{n}{layout} \PYG{o}{+=} \PYG{n}{field} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{North}
\PYG{n}{bp}\PYG{o}{.}\PYG{n}{layout} \PYG{o}{+=} \PYG{n}{button} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{Center}
\PYG{n}{frame}\PYG{o}{.}\PYG{n}{contents} \PYG{k}{=} \PYG{n}{bp}
\PYG{n}{frame}\PYG{o}{.}\PYG{n}{centerOnScreen}
\PYG{n}{frame}\PYG{o}{.}\PYG{n}{open}
\end{Verbatim}


\subsubsection{Simple Paint Example}
\label{cs2:simple-paint-example}
This example shows how you can override the paint method to make a
custom drawing. It also shows interactions with the mouse.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{import} \PYG{n+nn}{swing.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{event.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{java.awt.}\PYG{o}{\PYGZob{}}\PYG{n+nc}{Color}\PYG{o}{,}\PYG{n+nc}{Shape}\PYG{o}{\PYGZcb{}}
\PYG{k}{import} \PYG{n+nn}{java.awt.geom.\PYGZus{}}

\PYG{k}{var} \PYG{n}{dots} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{.}\PYG{n}{empty}\PYG{o}{[}\PYG{k+kt}{Shape}\PYG{o}{]}

\PYG{k}{val} \PYG{n}{panel} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Panel} \PYG{o}{\PYGZob{}}
  \PYG{k}{override} \PYG{k}{def} \PYG{n}{paint}\PYG{o}{(}\PYG{n}{g}\PYG{k}{:}\PYG{k+kt}{Graphics2D}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{white}\PYG{o}{)}
    \PYG{n}{g}\PYG{o}{.}\PYG{n}{fillRect}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,}\PYG{l+m+mi}{0}\PYG{o}{,}\PYG{n}{size}\PYG{o}{.}\PYG{n}{width}\PYG{o}{,}\PYG{n}{size}\PYG{o}{.}\PYG{n}{height}\PYG{o}{)}
    \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{black}\PYG{o}{)}
    \PYG{k}{for}\PYG{o}{(}\PYG{n}{s} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{n}{dots}\PYG{o}{)} \PYG{n}{g}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{n}{s}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
  \PYG{n}{listenTo}\PYG{o}{(}\PYG{n}{mouse}\PYG{o}{.}\PYG{n}{clicks}\PYG{o}{,}\PYG{n}{mouse}\PYG{o}{.}\PYG{n}{moves}\PYG{o}{)}
  \PYG{n}{reactions} \PYG{o}{+=} \PYG{o}{\PYGZob{}}
  \PYG{k}{case} \PYG{n}{mc}\PYG{k}{:} \PYG{k+kt}{MouseClicked} \PYG{o}{=\PYGZgt{}}
    \PYG{n}{dots} \PYG{o}{::=} \PYG{k}{new} \PYG{n+nc}{Ellipse2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{mc}\PYG{o}{.}\PYG{n}{point}\PYG{o}{.}\PYG{n}{x}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{mc}\PYG{o}{.}\PYG{n}{point}\PYG{o}{.}\PYG{n}{y}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{5}\PYG{o}{,}\PYG{l+m+mi}{5}\PYG{o}{)}
    \PYG{n}{repaint}
  \PYG{k}{case} \PYG{n}{mc}\PYG{k}{:} \PYG{k+kt}{MouseDragged} \PYG{o}{=\PYGZgt{}}
    \PYG{n}{dots} \PYG{o}{::=} \PYG{k}{new} \PYG{n+nc}{Ellipse2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{mc}\PYG{o}{.}\PYG{n}{point}\PYG{o}{.}\PYG{n}{x}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{mc}\PYG{o}{.}\PYG{n}{point}\PYG{o}{.}\PYG{n}{y}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{5}\PYG{o}{,}\PYG{l+m+mi}{5}\PYG{o}{)}
    \PYG{n}{repaint}
  \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}

\PYG{k}{val} \PYG{n}{frame} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{MainFrame} \PYG{o}{\PYGZob{}}
  \PYG{n}{contents} \PYG{k}{=} \PYG{n}{panel}
  \PYG{n}{size} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Dimension}\PYG{o}{(}\PYG{l+m+mi}{600}\PYG{o}{,}\PYG{l+m+mi}{600}\PYG{o}{)}
  \PYG{n}{centerOnScreen}
\PYG{o}{\PYGZcb{}}

\PYG{n}{frame}\PYG{o}{.}\PYG{n}{open}
\end{Verbatim}

Here's what the output looks like when you drag the mouse quasi-randomly on
the blank canvas that first comes appears. (Your output may vary!)

\includegraphics{SimplePaint.png}


\subsubsection{A More Complex GUI Example}
\label{cs2:a-more-complex-gui-example}
This is a large GUI example. There are two lists with a text fields and
some buttons. The first list is populated by the text field and the buttons
move things between lists or remove them from the second list.

The populating from the text field demonstrates how you listen to GUI
elements and react to them. The behavior of the lists shows how collection
methods can play a role in GUIs.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{import} \PYG{n+nn}{swing.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{event.\PYGZus{}}

\PYG{k}{val} \PYG{n}{list1} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{ListView}\PYG{o}{[}\PYG{k+kt}{String}\PYG{o}{]}\PYG{o}{(}\PYG{o}{)}
\PYG{k}{val} \PYG{n}{list2} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{ListView}\PYG{o}{[}\PYG{k+kt}{String}\PYG{o}{]}\PYG{o}{(}\PYG{o}{)}
\PYG{k}{val} \PYG{n}{buttons} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{FlowPanel} \PYG{o}{\PYGZob{}}
    \PYG{n}{contents} \PYG{o}{+=} \PYG{n+nc}{Button}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}\PYGZlt{}\PYGZhy{}\PYGZdq{}}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{list1}\PYG{o}{.}\PYG{n}{listData} \PYG{o}{++=} \PYG{n}{list2}\PYG{o}{.}\PYG{n}{selection}\PYG{o}{.}\PYG{n}{items}
        \PYG{n}{list2}\PYG{o}{.}\PYG{n}{listData} \PYG{k}{=} \PYG{n}{list2}\PYG{o}{.}\PYG{n}{listData}\PYG{o}{.}\PYG{n}{diff}\PYG{o}{(}\PYG{n}{list2}\PYG{o}{.}\PYG{n}{selection}\PYG{o}{.}\PYG{n}{items}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
    \PYG{n}{contents} \PYG{o}{+=} \PYG{n+nc}{Button}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}\PYGZhy{}\PYGZgt{}\PYGZdq{}}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{list2}\PYG{o}{.}\PYG{n}{listData} \PYG{o}{++=} \PYG{n}{list1}\PYG{o}{.}\PYG{n}{selection}\PYG{o}{.}\PYG{n}{items}
        \PYG{n}{list1}\PYG{o}{.}\PYG{n}{listData} \PYG{k}{=} \PYG{n}{list1}\PYG{o}{.}\PYG{n}{listData}\PYG{o}{.}\PYG{n}{diff}\PYG{o}{(}\PYG{n}{list1}\PYG{o}{.}\PYG{n}{selection}\PYG{o}{.}\PYG{n}{items}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
    \PYG{n}{contents} \PYG{o}{+=} \PYG{n+nc}{Button}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Remove\PYGZdq{}}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{list2}\PYG{o}{.}\PYG{n}{listData} \PYG{k}{=} \PYG{n}{list2}\PYG{o}{.}\PYG{n}{listData}\PYG{o}{.}\PYG{n}{diff}\PYG{o}{(}\PYG{n}{list2}\PYG{o}{.}\PYG{n}{selection}\PYG{o}{.}\PYG{n}{items}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\PYG{k}{val} \PYG{n}{field} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{TextField}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{listenTo}\PYG{o}{(}\PYG{k}{this}\PYG{o}{)}
    \PYG{n}{reactions} \PYG{o}{+=} \PYG{o}{\PYGZob{}}
    \PYG{k}{case} \PYG{n}{ed}\PYG{k}{:}
        \PYG{k+kt}{EditDone} \PYG{o}{=\PYGZgt{}}
\PYG{n}{list1}\PYG{o}{.}\PYG{n}{listData} \PYG{k}{:}
        \PYG{k+kt}{+=} \PYG{k+kt}{text}
        \PYG{n}{text} \PYG{k}{=} \PYG{l+s}{\PYGZdq{}\PYGZdq{}}
    \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}

\PYG{k}{val} \PYG{n}{frame} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{MainFrame} \PYG{o}{\PYGZob{}}
    \PYG{n}{contents} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{BorderPanel} \PYG{o}{\PYGZob{}}
        \PYG{k}{import} \PYG{n+nn}{BorderPanel.Position.\PYGZus{}}
        \PYG{n}{layout} \PYG{o}{+=} \PYG{n}{field} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{North}
        \PYG{n}{layout} \PYG{o}{+=} \PYG{k}{new} \PYG{n+nc}{ScrollPane}\PYG{o}{(}\PYG{n}{list1}\PYG{o}{)} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{West}
        \PYG{n}{layout} \PYG{o}{+=} \PYG{k}{new} \PYG{n+nc}{ScrollPane}\PYG{o}{(}\PYG{n}{list2}\PYG{o}{)} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{East}
        \PYG{n}{layout} \PYG{o}{+=} \PYG{n}{buttons} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n+nc}{Center}
    \PYG{o}{\PYGZcb{}}
    \PYG{n}{size} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Dimension}\PYG{o}{(}\PYG{l+m+mi}{600}\PYG{o}{,}\PYG{l+m+mi}{500}\PYG{o}{)}
    \PYG{n}{centerOnScreen}
\PYG{o}{\PYGZcb{}}

\PYG{n}{frame}\PYG{o}{.}\PYG{n}{open}
\end{Verbatim}


\subsubsection{Asteroids}
\label{cs2:asteroids}
This program is a little implementation of asteroids. It shows keyboard
events and the use of case classes to group data together.

We start by importing varius dependencies. This shows how you can take advantage of
existing Java libraries.

Case classes are used to maintain information about key elements of the game, notably
the asteroids and bullets. Although you see the word class here, we're primarily using
class to aggregate the data (think about C \emph{struct} but even nicer). These are used to
maintain two typesafe lists of asteroids and bullets, respectively, with type \code{List{[}Asteroid{]}}
and \code{List{[}Bullet{]}}.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{import} \PYG{n+nn}{swing.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{event.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{java.awt.}\PYG{o}{\PYGZob{}}\PYG{n+nc}{Color}\PYG{o}{,}\PYG{n+nc}{Shape}\PYG{o}{\PYGZcb{}}
\PYG{k}{import} \PYG{n+nn}{java.awt.geom.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{javax.swing.Timer}

\PYG{k}{case} \PYG{k}{class} \PYG{n+nc}{Asteroid}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{y}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{vx}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{vy}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{size}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{)}
\PYG{k}{case} \PYG{k}{class} \PYG{n+nc}{Bullet}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{y}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{vx}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{vy}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{,}\PYG{n}{age}\PYG{k}{:}\PYG{k+kt}{Int}\PYG{o}{)}

\PYG{k}{val} \PYG{n}{windowSize} \PYG{k}{=} \PYG{l+m+mi}{600}
\PYG{k}{val} \PYG{n}{shipSize} \PYG{k}{=} \PYG{l+m+mi}{6}

\PYG{k}{var} \PYG{n}{asteroids} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{l+m+mi}{5}\PYG{o}{)}\PYG{o}{\PYGZob{}}
    \PYG{k}{val} \PYG{n}{theta} \PYG{k}{=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n+nc}{Pi}\PYG{o}{*}\PYG{l+m+mi}{2}
    \PYG{n+nc}{Asteroid}\PYG{o}{(}\PYG{n}{windowSize}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{+}\PYG{n}{math}\PYG{o}{.}\PYG{n}{cos}\PYG{o}{(}\PYG{n}{theta}\PYG{o}{)}\PYG{o}{*}\PYG{n}{windowSize}\PYG{o}{/}\PYG{l+m+mi}{4}\PYG{o}{,}
                   \PYG{n}{windowSize}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{+}\PYG{n}{math}\PYG{o}{.}\PYG{n}{sin}\PYG{o}{(}\PYG{n}{theta}\PYG{o}{)}\PYG{o}{*}\PYG{n}{windowSize}\PYG{o}{/}\PYG{l+m+mi}{4}\PYG{o}{,}
                     \PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{o}{,}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{o}{,}\PYG{l+m+mi}{50}\PYG{o}{)}
\PYG{o}{\PYGZcb{}}
\PYG{k}{var} \PYG{n}{bullets} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{[}\PYG{k+kt}{Bullet}\PYG{o}{]}\PYG{o}{(}\PYG{o}{)}
\PYG{k}{var} \PYG{n}{shipX} \PYG{k}{=} \PYG{n}{windowSize}\PYG{o}{/}\PYG{l+m+mf}{2.0}
\PYG{k}{var} \PYG{n}{shipY} \PYG{k}{=} \PYG{n}{windowSize}\PYG{o}{/}\PYG{l+m+mf}{2.0}
\PYG{k}{var} \PYG{n}{heading} \PYG{k}{=} \PYG{l+m+mf}{0.0}
\PYG{k}{var} \PYG{n}{shipVx} \PYG{k}{=} \PYG{l+m+mf}{0.0}
\PYG{k}{var} \PYG{n}{shipVy} \PYG{k}{=} \PYG{l+m+mf}{0.0}
\PYG{k}{var} \PYG{n}{leftDown} \PYG{k}{=} \PYG{k+kc}{false}
\PYG{k}{var} \PYG{n}{rightDown} \PYG{k}{=} \PYG{k+kc}{false}
\end{Verbatim}

The \code{wrap()} method does what you might be thinking it does. It takes an x
or y coordinate (even though you only see \code{x} in the parameter name) of a
given asteroid and ensures it falls within the bounds of the window. Note that
this references an external ``global'' \emph{value} \code{windowSize}. Because this
value is immutable, there is no risk of a side effect. (This could be called
the revival of the \code{const} from C/C++ and Pascal but in a more modern
formulation.)

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{def} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:}\PYG{k+kt}{Double}\PYG{o}{)}\PYG{k}{:}\PYG{k+kt}{Double} \PYG{o}{=} \PYG{o}{\PYGZob{}}
    \PYG{k}{var} \PYG{n}{nx} \PYG{k}{=} \PYG{n}{x}
    \PYG{k}{while}\PYG{o}{(}\PYG{n}{nx} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{n}{nx} \PYG{o}{+=} \PYG{n}{windowSize}
    \PYG{k}{while}\PYG{o}{(}\PYG{n}{nx} \PYG{o}{\PYGZgt{}} \PYG{n}{windowSize}\PYG{o}{)} \PYG{n}{nx} \PYG{o}{\PYGZhy{}=} \PYG{n}{windowSize}
    \PYG{n}{nx}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

The definition of the panel is where the actual drawing (and redrawing) of the game
takes place. It also shows how to clearly separate the drawing from the reactions to
events of interest (keyboard and mouse). Notably, we can handle these events
without having to use \emph{classes}. This allows us to stay focused on design principles
instead of the vagaries of event objects and interfaces (even though these details
are still present, being able to match the event's \emph{type} allows us to avoid
premature complexity from a student perspective.)

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{val} \PYG{n}{panel} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Panel} \PYG{o}{\PYGZob{}}
    \PYG{k}{override} \PYG{k}{def} \PYG{n}{paint}\PYG{o}{(}\PYG{n}{g}\PYG{k}{:}\PYG{k+kt}{Graphics2D}\PYG{o}{)} \PYG{o}{\PYGZob{}}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{black}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{fillRect}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,}\PYG{l+m+mi}{0}\PYG{o}{,}\PYG{n}{size}\PYG{o}{.}\PYG{n}{width}\PYG{o}{,}\PYG{n}{size}\PYG{o}{.}\PYG{n}{height}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{lightGray}\PYG{o}{)}
        \PYG{k}{for}\PYG{o}{(}\PYG{n}{a} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{n}{asteroids}\PYG{o}{)} \PYG{n}{g}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{k}{new} \PYG{n+nc}{Ellipse2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{a}\PYG{o}{.}\PYG{n}{x}\PYG{o}{\PYGZhy{}}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{y}\PYG{o}{\PYGZhy{}}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{)}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{red}\PYG{o}{)}
        \PYG{k}{for}\PYG{o}{(}\PYG{n}{b} \PYG{k}{\PYGZlt{}\PYGZhy{}} \PYG{n}{bullets}\PYG{o}{)} \PYG{n}{g}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{k}{new} \PYG{n+nc}{Rectangle2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{b}\PYG{o}{.}\PYG{n}{x}\PYG{o}{,}\PYG{n}{b}\PYG{o}{.}\PYG{n}{y}\PYG{o}{,}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{blue}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{k}{new} \PYG{n+nc}{Ellipse2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{shipX}\PYG{o}{\PYGZhy{}}\PYG{n}{shipSize}\PYG{o}{,}\PYG{n}{shipY}\PYG{o}{\PYGZhy{}}\PYG{n}{shipSize}\PYG{o}{,}\PYG{n}{shipSize}\PYG{o}{*}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{shipSize}\PYG{o}{*}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{setPaint}\PYG{o}{(}\PYG{n+nc}{Color}\PYG{o}{.}\PYG{n}{green}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{draw}\PYG{o}{(}\PYG{k}{new} \PYG{n+nc}{Ellipse2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{shipX}\PYG{o}{\PYGZhy{}}\PYG{n}{shipSize}\PYG{o}{,}\PYG{n}{shipY}\PYG{o}{\PYGZhy{}}\PYG{n}{shipSize}\PYG{o}{,}\PYG{n}{shipSize}\PYG{o}{*}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{shipSize}\PYG{o}{*}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{)}
        \PYG{n}{g}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{k}{new} \PYG{n+nc}{Ellipse2D}\PYG{o}{.}\PYG{n+nc}{Double}\PYG{o}{(}\PYG{n}{shipX}\PYG{o}{+}\PYG{o}{(}\PYG{n}{shipSize}\PYG{o}{+}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n}{cos}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{n}{shipY}\PYG{o}{+}\PYG{o}{(}\PYG{n}{shipSize}\PYG{o}{+}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n}{sin}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{2}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{,}\PYG{l+m+mi}{4}\PYG{o}{)}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
    \PYG{n}{listenTo}\PYG{o}{(}\PYG{n}{keys}\PYG{o}{,}\PYG{n}{mouse}\PYG{o}{.}\PYG{n}{clicks}\PYG{o}{)}
    \PYG{n}{reactions} \PYG{o}{+=} \PYG{o}{\PYGZob{}}
        \PYG{k}{case} \PYG{n}{kp}\PYG{k}{:}\PYG{k+kt}{KeyPressed} \PYG{o}{=\PYGZgt{}}
            \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Left}\PYG{o}{)} \PYG{n}{leftDown} \PYG{k}{=} \PYG{k+kc}{true}
            \PYG{k}{else} \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Right}\PYG{o}{)} \PYG{n}{rightDown} \PYG{k}{=} \PYG{k+kc}{true}
            \PYG{k}{else} \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Up}\PYG{o}{)} \PYG{o}{\PYGZob{}}
                \PYG{n}{shipVx} \PYG{o}{+=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{cos}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{*}\PYG{l+m+mf}{0.2}
                \PYG{n}{shipVy} \PYG{o}{+=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{sin}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{*}\PYG{l+m+mf}{0.2}
            \PYG{o}{\PYGZcb{}} \PYG{k}{else} \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Down}\PYG{o}{)} \PYG{o}{\PYGZob{}}
                \PYG{n}{shipVx} \PYG{o}{\PYGZhy{}=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{cos}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{*}\PYG{l+m+mf}{0.2}
                \PYG{n}{shipVy} \PYG{o}{\PYGZhy{}=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{sin}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{*}\PYG{l+m+mf}{0.2}
            \PYG{o}{\PYGZcb{}} \PYG{k}{else} \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Space}\PYG{o}{)} \PYG{o}{\PYGZob{}}
                \PYG{n}{bullets} \PYG{o}{::=} \PYG{n+nc}{Bullet}\PYG{o}{(}\PYG{n}{shipX}\PYG{o}{+}\PYG{o}{(}\PYG{n}{shipSize}\PYG{o}{+}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n}{cos}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{,}\PYG{n}{shipY}\PYG{o}{+}\PYG{o}{(}\PYG{n}{shipSize}\PYG{o}{+}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n}{sin}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{,}\PYG{n}{shipVx}\PYG{o}{+}\PYG{l+m+mi}{3}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n}{cos}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{,}\PYG{n}{shipVy}\PYG{o}{+}\PYG{l+m+mi}{3}\PYG{o}{*}\PYG{n}{math}\PYG{o}{.}\PYG{n}{sin}\PYG{o}{(}\PYG{n}{heading}\PYG{o}{)}\PYG{o}{,}\PYG{l+m+mi}{0}\PYG{o}{)}
            \PYG{o}{\PYGZcb{}}
        \PYG{k}{case} \PYG{n}{kp}\PYG{k}{:}\PYG{k+kt}{KeyReleased} \PYG{o}{=\PYGZgt{}}
            \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Left}\PYG{o}{)} \PYG{n}{leftDown} \PYG{k}{=} \PYG{k+kc}{false}
            \PYG{k}{else} \PYG{k}{if}\PYG{o}{(}\PYG{n}{kp}\PYG{o}{.}\PYG{n}{key} \PYG{o}{==} \PYG{n+nc}{Key}\PYG{o}{.}\PYG{n+nc}{Right}\PYG{o}{)} \PYG{n}{rightDown} \PYG{k}{=} \PYG{k+kc}{false}
        \PYG{k}{case} \PYG{n}{me}\PYG{k}{:}\PYG{k+kt}{MouseEntered} \PYG{o}{=\PYGZgt{}} \PYG{n}{requestFocus}
    \PYG{o}{\PYGZcb{}}
    \PYG{n}{preferredSize} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{Dimension}\PYG{o}{(}\PYG{n}{windowSize}\PYG{o}{,}\PYG{n}{windowSize}\PYG{o}{)}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

A \emph{timer} is particularly useful in game design, where you want to have self-updating without
user interaction. In the case of this game, whether or not the user is doing anything, asteroids
continue moving, subject to their velocities. Same for bullets. There is also logic to determine
collisions and whether the ship is destroyed (which ends the game).

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{val} \PYG{n}{timer}\PYG{k}{:}\PYG{k+kt}{Timer} \PYG{o}{=} \PYG{k}{new} \PYG{n+nc}{Timer}\PYG{o}{(}\PYG{l+m+mi}{10}\PYG{o}{,}\PYG{n+nc}{Swing}\PYG{o}{.}\PYG{n+nc}{ActionListener}\PYG{o}{(}\PYG{n}{e} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
    \PYG{k}{if}\PYG{o}{(}\PYG{n}{leftDown}\PYG{o}{)} \PYG{n}{heading} \PYG{o}{\PYGZhy{}=} \PYG{n}{math}\PYG{o}{.}\PYG{n+nc}{Pi}\PYG{o}{/}\PYG{l+m+mi}{40} 
    \PYG{k}{if}\PYG{o}{(}\PYG{n}{rightDown}\PYG{o}{)} \PYG{n}{heading} \PYG{o}{+=} \PYG{n}{math}\PYG{o}{.}\PYG{n+nc}{Pi}\PYG{o}{/}\PYG{l+m+mi}{40}
    \PYG{n}{asteroids} \PYG{k}{=} \PYG{n}{asteroids}\PYG{o}{.}\PYG{n}{map}\PYG{o}{(}\PYG{n}{a} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
        \PYG{n}{a}\PYG{o}{.}\PYG{n}{copy}\PYG{o}{(}\PYG{n}{x} \PYG{k}{=} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{a}\PYG{o}{.}\PYG{n}{x}\PYG{o}{+}\PYG{n}{a}\PYG{o}{.}\PYG{n}{vx}\PYG{o}{)}\PYG{o}{,} \PYG{n}{y} \PYG{k}{=} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{a}\PYG{o}{.}\PYG{n}{y}\PYG{o}{+}\PYG{n}{a}\PYG{o}{.}\PYG{n}{vy}\PYG{o}{)}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}\PYG{o}{)}
    \PYG{n}{shipX} \PYG{k}{=} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{shipX}\PYG{o}{+}\PYG{n}{shipVx}\PYG{o}{)}
    \PYG{n}{shipY} \PYG{k}{=} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{shipY}\PYG{o}{+}\PYG{n}{shipVy}\PYG{o}{)}
    \PYG{k}{var} \PYG{n}{hit} \PYG{k}{=} \PYG{n+nc}{List}\PYG{o}{[}\PYG{k+kt}{Asteroid}\PYG{o}{]}\PYG{o}{(}\PYG{o}{)}
    \PYG{n}{bullets} \PYG{k}{=} \PYG{n}{bullets}\PYG{o}{.}\PYG{n}{map}\PYG{o}{(}\PYG{n}{b} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
        \PYG{n}{b}\PYG{o}{.}\PYG{n}{copy}\PYG{o}{(}\PYG{n}{x} \PYG{k}{=} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{b}\PYG{o}{.}\PYG{n}{x}\PYG{o}{+}\PYG{n}{b}\PYG{o}{.}\PYG{n}{vx}\PYG{o}{)}\PYG{o}{,} \PYG{n}{y} \PYG{k}{=} \PYG{n}{wrap}\PYG{o}{(}\PYG{n}{b}\PYG{o}{.}\PYG{n}{y}\PYG{o}{+}\PYG{n}{b}\PYG{o}{.}\PYG{n}{vy}\PYG{o}{)}\PYG{o}{,} \PYG{n}{age} \PYG{k}{=} \PYG{n}{b}\PYG{o}{.}\PYG{n}{age}\PYG{o}{+}\PYG{l+m+mi}{1}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{.}\PYG{n}{filter}\PYG{o}{(}\PYG{n}{b} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
        \PYG{n}{b}\PYG{o}{.}\PYG{n}{age}\PYG{o}{\PYGZlt{}}\PYG{l+m+mi}{100} \PYG{o}{\PYGZam{}\PYGZam{}} \PYG{n}{asteroids}\PYG{o}{.}\PYG{n}{forall}\PYG{o}{(}\PYG{n}{a} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
            \PYG{k}{val} \PYG{n}{dx} \PYG{k}{=} \PYG{n}{b}\PYG{o}{.}\PYG{n}{x}\PYG{o}{\PYGZhy{}}\PYG{n}{a}\PYG{o}{.}\PYG{n}{x}
            \PYG{k}{val} \PYG{n}{dy} \PYG{k}{=} \PYG{n}{b}\PYG{o}{.}\PYG{n}{y}\PYG{o}{\PYGZhy{}}\PYG{n}{a}\PYG{o}{.}\PYG{n}{y}
            \PYG{k}{val} \PYG{n}{dsqr} \PYG{k}{=} \PYG{n}{dx}\PYG{o}{*}\PYG{n}{dx}\PYG{o}{+}\PYG{n}{dy}\PYG{o}{*}\PYG{n}{dy}
            \PYG{k}{val} \PYG{n}{isHit} \PYG{k}{=} \PYG{n}{dsqr} \PYG{o}{\PYGZlt{}} \PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{*}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{/}\PYG{l+m+mi}{4}
            \PYG{k}{if}\PYG{o}{(}\PYG{n}{isHit}\PYG{o}{)} \PYG{n}{hit} \PYG{o}{::=} \PYG{n}{a}
            \PYG{o}{!}\PYG{n}{isHit}
        \PYG{o}{\PYGZcb{}}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}\PYG{o}{)}
    \PYG{n}{asteroids} \PYG{k}{=} \PYG{n}{asteroids}\PYG{o}{.}\PYG{n}{flatMap}\PYG{o}{(}\PYG{n}{a} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
        \PYG{k}{if}\PYG{o}{(}\PYG{n}{hit}\PYG{o}{.}\PYG{n}{contains}\PYG{o}{(}\PYG{n}{a}\PYG{o}{)}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{k}{if}\PYG{o}{(}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size} \PYG{o}{\PYGZlt{}=}\PYG{l+m+mi}{10}\PYG{o}{)} \PYG{n+nc}{List}\PYG{o}{(}\PYG{o}{)}
            \PYG{k}{else} \PYG{n+nc}{List}\PYG{o}{.}\PYG{n}{fill}\PYG{o}{(}\PYG{l+m+mi}{4}\PYG{o}{)}\PYG{o}{(}\PYG{n+nc}{Asteroid}\PYG{o}{(}\PYG{n}{a}\PYG{o}{.}\PYG{n}{x}\PYG{o}{+}\PYG{o}{(}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{o}{)}\PYG{o}{*}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{y}\PYG{o}{+}\PYG{o}{(}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{o}{)}\PYG{o}{*}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{vx}\PYG{o}{+}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{vy}\PYG{o}{+}\PYG{n}{math}\PYG{o}{.}\PYG{n}{random}\PYG{o}{\PYGZhy{}}\PYG{l+m+mf}{0.5}\PYG{o}{,}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{)}
        \PYG{o}{\PYGZcb{}} \PYG{k}{else} \PYG{n+nc}{List}\PYG{o}{(}\PYG{n}{a}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}\PYG{o}{)}
    \PYG{k}{if}\PYG{o}{(}\PYG{n}{asteroids}\PYG{o}{.}\PYG{n}{exists}\PYG{o}{(}\PYG{n}{a} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
            \PYG{k}{val} \PYG{n}{dx} \PYG{k}{=} \PYG{n}{shipX}\PYG{o}{\PYGZhy{}}\PYG{n}{a}\PYG{o}{.}\PYG{n}{x}
            \PYG{k}{val} \PYG{n}{dy} \PYG{k}{=} \PYG{n}{shipY}\PYG{o}{\PYGZhy{}}\PYG{n}{a}\PYG{o}{.}\PYG{n}{y}
            \PYG{k}{val} \PYG{n}{dsqr} \PYG{k}{=} \PYG{n}{dx}\PYG{o}{*}\PYG{n}{dx}\PYG{o}{+}\PYG{n}{dy}\PYG{o}{*}\PYG{n}{dy}
            \PYG{n}{dsqr} \PYG{o}{\PYGZlt{}} \PYG{o}{(}\PYG{n}{shipSize}\PYG{o}{+}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{*}\PYG{o}{(}\PYG{n}{shipSize}\PYG{o}{+}\PYG{n}{a}\PYG{o}{.}\PYG{n}{size}\PYG{o}{/}\PYG{l+m+mi}{2}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{)} \PYG{n}{timer}\PYG{o}{.}\PYG{n}{stop}\PYG{o}{(}\PYG{o}{)}
    \PYG{n}{panel}\PYG{o}{.}\PYG{n}{repaint}
\PYG{o}{\PYGZcb{}}\PYG{o}{)}\PYG{o}{)}
\end{Verbatim}

Setup of the game is fairly concise. Create the main (Swing) frame and set the desired properties.
In particular, we embed the created panel (a method that is familiar to anyone who has taught Java
based UIs using AWT or Swing) and disallow frame resizing. We also center the frame on the screen
(if supported). Then we display the frame and start the timer.

While there are a few details about Swing to know here, much of this code is common to all Swing
application development, so it is eminently teachable--and you can always point students to the
basic documentation for Java to learn the details.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{val} \PYG{n}{frame} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{MainFrame} \PYG{o}{\PYGZob{}}
    \PYG{n}{contents} \PYG{k}{=} \PYG{n}{panel}
    \PYG{n}{resizable} \PYG{k}{=} \PYG{k+kc}{false}
    \PYG{n}{centerOnScreen}
\PYG{o}{\PYGZcb{}}

\PYG{n}{frame}\PYG{o}{.}\PYG{n}{open}
\PYG{n}{panel}\PYG{o}{.}\PYG{n}{requestFocus}
\PYG{n}{timer}\PYG{o}{.}\PYG{n}{start}
\end{Verbatim}

Here's a screenshot of the game:

\includegraphics{SimpleGame.png}


\subsection{CS2}
\label{cs2:id1}\begin{itemize}
\item {} 
Pure OO

\item {} 
Fewer quirks than Java

\item {} 
Powerful type system

\item {} 
Traits

\item {} 
Rich collections

\item {} 
Libraries again

\item {} 
Can make things interesting/relevant

\item {} 
Multithreading and networking

\item {} 
Eclipse (maybe) and IntelliJ (our favorite)

\item {} 
Scalable language

\item {} 
Libraries as language

\item {} 
Special methods

\end{itemize}


\section{Build Tools for Scala}
\label{buildtools:build-tools-for-scala}\label{buildtools::doc}
In this section, we provide a brief overview of build tools for
Scala. In general, build tools support the build process in several
ways:
\begin{itemize}
\item {} 
structured representation of the project dependency graph

\item {} 
management of the build lifecycle (compile, test, run)

\item {} 
management of external dependencies

\end{itemize}


\subsection{Why Use a Build Tool?}
\label{buildtools:why-use-a-build-tool}
When using the Java or Scala command-line tools, the developer is
responsible for setting the dreaded classpath. This can quickly become
unwieldy when dependencies even as simple as JUnit are involved, so
this is not something you would usually want to do manually.


\subsection{Brief History of Build Tools}
\label{buildtools:brief-history-of-build-tools}\begin{description}
\item[{Unix make, Apache ant}] \leavevmode
These tools manage the build lifecycle but not external dependencies.

\item[{Apache maven}] \leavevmode
This tool also manages external dependencies but requires a lot of
XML-based configuraration.

\end{description}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{n+nt}{\PYGZlt{}dependency}\PYG{n+nt}{\PYGZgt{}}
              \PYG{n+nt}{\PYGZlt{}groupId}\PYG{n+nt}{\PYGZgt{}}org.restlet\PYG{n+nt}{\PYGZlt{}/groupId\PYGZgt{}}
              \PYG{n+nt}{\PYGZlt{}artifactId}\PYG{n+nt}{\PYGZgt{}}org.restlet.ext.spring\PYG{n+nt}{\PYGZlt{}/artifactId\PYGZgt{}}
              \PYG{n+nt}{\PYGZlt{}version}\PYG{n+nt}{\PYGZgt{}}\PYGZdl{}\PYGZob{}restlet.version\PYGZcb{}\PYG{n+nt}{\PYGZlt{}/version\PYGZgt{}}
      \PYG{n+nt}{\PYGZlt{}/dependency\PYGZgt{}}
\end{Verbatim}
\begin{description}
\item[{Apache ivy, Gradle, Scala's \href{http://www.scala-sbt.org}{Simple Build Tool (sbt)}, etc.}] \leavevmode
These tools emphasize convention over configuration in support of
agile development processes. sbt is compatible with ivy and designed
primarily for Scala development. For example, ivy uses a structured
but lighter-weight format:

\end{description}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{n+nt}{\PYGZlt{}dependency} \PYG{n+na}{org=}\PYG{l+s}{\PYGZdq{}junit\PYGZdq{}} \PYG{n+na}{name=}\PYG{l+s}{\PYGZdq{}junit\PYGZdq{}} \PYG{n+na}{rev=}\PYG{l+s}{\PYGZdq{}4.11\PYGZdq{}}\PYG{n+nt}{/\PYGZgt{}}
\end{Verbatim}


\subsection{sbt}
\label{buildtools:sbt}
In the simplest case, sbt does not require any configuration and will
use reasonable defaults. The project layout is similar to that used by
Maven:
\begin{itemize}
\item {} 
Production code goes in \code{src/main/scala}.

\item {} 
Test code goes in \code{src/test/scala}.

\end{itemize}

sbt supports two configuration styles, one based on a simple
Scala-based domain-specific language, and one based on the full Scala
language for configuring all aspects of a project.


\subsubsection{build.sbt format}
\label{buildtools:build-sbt-format}
A minimal sbt \code{build.sbt} file would look like this. The empty lines
are required, and the file must be placed in the project root folder.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{n}{name} \PYG{o}{:=} \PYG{l+s}{\PYGZdq{}integration\PYGZhy{}scala\PYGZdq{}}

  \PYG{n}{version} \PYG{o}{:=} \PYG{l+s}{\PYGZdq{}0.0.2\PYGZdq{}}
\end{Verbatim}

Additional dependencies can be specified either one at a time

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{n}{libraryDependencies} \PYG{o}{+=} \PYG{l+s}{\PYGZdq{}com.novocode\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}junit\PYGZhy{}interface\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}0.10\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}test\PYGZdq{}}
\end{Verbatim}

or as a group

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{n}{libraryDependencies} \PYG{o}{++=} \PYG{n+nc}{Seq}\PYG{o}{(}
    \PYG{l+s}{\PYGZdq{}org.scala\PYGZhy{}lang\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}scala\PYGZhy{}actors\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}2.10.1\PYGZdq{}}\PYG{o}{,}
    \PYG{l+s}{\PYGZdq{}com.novocode\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}junit\PYGZhy{}interface\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}0.10\PYGZdq{}} \PYG{o}{\PYGZpc{}} \PYG{l+s}{\PYGZdq{}test\PYGZdq{}}
  \PYG{o}{)}
\end{Verbatim}


\subsubsection{Build.scala format}
\label{buildtools:build-scala-format}
Examples of more complex Scala-based project configurations can be
found in these examples:
\begin{itemize}
\item {} 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/clickcounter-android-scala/src/tip/project/}{Android click counter app}

\item {} 
\href{https://bitbucket.org/loyolachicagocs\_distributed/primenumbers-spray-scala/src/master/project/}{Prime checker web service}

\end{itemize}


\subsection{Plugin Ecosystem}
\label{buildtools:plugin-ecosystem}
sbt includes a growing plugin ecosystem. Key examples include
\begin{description}
\item[{\href{https://github.com/typesafehub/sbteclipse}{sbteclipse}}] \leavevmode
automatically generates an Eclipse project configuration from an sbt one.

\item[{\href{https://github.com/sbt/sbt-start-script}{sbt-start-script}}] \leavevmode
generates a start script for running a Scala application outside of
sbt.

\end{description}

The IntelliJ IDEA Scala plugin also integrates directly with sbt.


\section{Web Application and Services}
\label{webservices:web-application-and-services}\label{webservices::doc}

\subsection{Professional Context}
\label{webservices:professional-context}
\emph{Disclaimer: I am not affiliated in any form with Typesafe.}

In this section, we discuss how Scala can enhance the pedagogy in
certain foundational and applied advanced courses. Given that the
majority of students coming out of our undergraduate and graduate
programs find jobs in local and global industry, we place considerable
emphasis on professional practice.

To this end, we draw on several (local and global) resources:
\begin{itemize}
\item {} 
\href{http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod}{Uncle Bob}

\item {} 
\href{http://www.thoughtworks.com/radar}{ThoughtWorks Technology Radar}

\item {} 
\href{http://www.se-radio.net}{IEEE Software's Software Engineering Radio}

\end{itemize}

We attempt to strike a balance among solid foundational knowledge,
state-of-the-art technology, and job market demands. In particular, we
have adopted the following rule for our advanced courses and research
projects: \emph{new code in Java (the language, as opposed to the
platform)}.

We also strive to choose technologies that scale properly. Here, the
typical startup story goes like this: Implement in RoR, oops, it
doesn't scale, then redo in guess what language? There are an
increasing number of good language and platform choices here, and in
our experience, Scala is one of them.

The job market is also increasingly interested in Scala. \href{http://jobs.cs.luc.edu/post/41214148685/telecommuting-internships-and-full-time-positions-at}{Here}
is an interesting local internship ad.


\subsection{Curricular Context}
\label{webservices:curricular-context}
Starting in 2010, we have been incorporating Scala into several of
these courses, taught mostly by Konstantin and experienced
professionals serving as adjuncts.
\begin{itemize}
\item {} 
\href{http://laufer.cs.luc.edu/teaching/473}{COMP 373/473: Advanced Object-Oriented Development},
using Scala since spring 2010, planning to add Android in spring 2014

\item {} 
\href{http://laufer.cs.luc.edu/teaching/372}{COMP 372/471: Theory (and Practice) of Programming Languages},
using Haskell (and some F\#) since fall 2010

\item {} 
\href{http://laufer.cs.luc.edu/teaching/442}{COMP 338/442: Server-Side Software Development}
(focusing on web applications), using Scala with the
\href{http://www.playframework.com/}{Play! framework} since fall 2010

\item {} 
\href{http://laufer.cs.luc.edu/teaching/433}{COMP 388/433: Web Services Development},
using Scala with the \href{http://spray.io}{spray toolkit}
since spring 2011

\item {} 
\href{http://laufer.cs.luc.edu/teaching/313}{COMP 313/413: Intermediate Object-Oriented Development}
(focusing on software design and architecture), using Java with Android since fall 2012,
considering the addition of Scala down the road

\end{itemize}


\subsection{Why Scala?}
\label{webservices:why-scala}
In our experience, Scala can help with the pedagogy of advanced
applied courses in multiple ways:
\begin{itemize}
\item {} 
less boilerplate

\item {} 
focus on deep concepts

\item {} 
focus on good practices

\end{itemize}

In the remainder of this section, we will give an overview of web
application and web service development in Scala and contrast the
experience with the corresponding Java-based techniques.


\subsection{Web Applications}
\label{webservices:web-applications}
The predominant web application frameworks targeting Scala are \href{http://liftweb.net}{Lift} and \href{http://playframework.com}{Play!}.
Typesafe has adopted the latter as part of its \href{http://typesafe.com/stack}{official stack}, and we had actually started to use
Play! in our course before Typesafe's decision was known.

The primary concerns in the development of web application for human
users---as opposed to a web service for programmatic consumption---are
\begin{itemize}
\item {} \begin{description}
\item[{views}] \leavevmode\begin{itemize}
\item {} 
presentation

\item {} 
visual styles

\item {} 
layout

\item {} 
navigation

\item {} 
i18n

\end{itemize}

\end{description}

\item {} \begin{description}
\item[{controllers}] \leavevmode\begin{itemize}
\item {} 
validation

\item {} 
authentication

\item {} 
dynamic behavior/interaction/state

\end{itemize}

\end{description}

\item {} \begin{description}
\item[{models}] \leavevmode\begin{itemize}
\item {} 
services

\item {} 
domain model

\end{itemize}

\end{description}

\item {} \begin{description}
\item[{persistence}] \leavevmode\begin{itemize}
\item {} 
database technologies

\item {} 
mapping domain object to persistent storage

\end{itemize}

\end{description}

\item {} \begin{description}
\item[{testing}] \leavevmode\begin{itemize}
\item {} 
unit testing

\item {} 
integration testing

\item {} 
functional testing

\item {} 
acceptance testing

\item {} 
performance/load testing

\end{itemize}

\end{description}

\end{itemize}

When using a Java-based stack, we typically address these concerns
with a stack tied together by a dependency-injection framework such as
Spring and an object-relational mapper (ORM) such as Hibernate, along
with a MVC framework for the upper layers.

When using a Scala-based stack, we an express an equivalent
architecture much more concisely and using language mechanisms instead
of requiring a DI framework.


\subsubsection{Examples}
\label{webservices:examples}\begin{itemize}
\item {} 
\href{https://github.com/webapps-cs-luc-edu/linreg-stripes-spring-maven}{Linear regression in Java with Spring, Stripes, and maven}

\item {} 
\href{https://github.com/webapps-cs-luc-edu/todolist-play-scala}{To-do list in Scala with Play!}

\item {} 
\href{http://laufer-todolist-play-scala.herokuapp.com}{Live version of the to-do list deployed to the cloud}

\end{itemize}


\subsection{Web Services}
\label{webservices:web-services}
As opposed to the Simple Object Access Protocol (SOAP), we will focus
on representational state transfer (REST), which has emerged as the
preferred approach of the broader agile community.

The implementing-rest community has put together a helpful
\href{https://code.google.com/p/implementing-rest/wiki/ByLanguage}{language matrix}
of REST libraries, toolkits, and frameworks. Typesafe's stack does not
yet include strong support for RESTful web services in the sense of
a high-level DSL for request routing, which is where some of the
choices in the language matrix come into the picture.

We have picked \href{http://spray.io}{spray} not only because the author is from
Konstantin's home town but also because it is:
\begin{itemize}
\item {} 
concise

\item {} 
flexible

\item {} 
type-safe

\item {} 
focus on HTTP and request routing

\item {} 
more and more widely used and supported

\end{itemize}

Scala and Spray are supported by \href{https://devcenter.heroku.com/articles/scala}{Heroku}
and several other newer APaaS cloud providers. Deploying a service to the cloud requires
a simple Git commit; this makes it possible to achieve continuous delivery.


\subsubsection{Examples}
\label{webservices:id1}\begin{itemize}
\item {} 
\href{https://github.com/webservices-cs-luc-edu/bookmarks-restlet-spring-java}{Social bookmarking example based on Java with the Restlet framework}

\item {} 
\href{https://github.com/webservices-cs-luc-edu/primenumbers-spray-scala}{Prime number checker based on Scala with spray}

\end{itemize}


\section{Mobile Application Development with Android}
\label{android::doc}\label{android:mobile-application-development-with-android}
Mobile applications backed by cloud-based RESTful services have emerged as the
primary face of computing in terms of massive consumer
participation. Jason Christensen described this system architecture in
his \href{http://www.slideshare.net/jasonc411/oopsla-2009-combining-rest-and-cloud-a-practitioners-report}{OOPSLA 2009 presentation}.
Therefore, not only do we find it important to cover this system
architecture in the curriculum, but we also see this architecture as a
very effective context for teaching various important computer science topics:
\begin{itemize}
\item {} \begin{description}
\item[{(real-world) software architecture}] \leavevmode\begin{itemize}
\item {} 
dependency inversion principle (DIP)

\item {} 
model-view-adapter architectural pattern (MVA)

\item {} 
testability

\item {} 
etc.

\end{itemize}

\end{description}

\item {} \begin{description}
\item[{concurrent, parallel, and distributed computing topics (PDC/TCPP/EduPar)}] \leavevmode\begin{itemize}
\item {} 
events

\item {} 
timers (one-shot and recurring)

\item {} 
background threads

\item {} 
offloading tasks to the cloud

\end{itemize}

\end{description}

\item {} \begin{description}
\item[{embedded/resource-conscious computing}] \leavevmode\begin{itemize}
\item {} 
limitations of the device

\item {} 
capabilities of the device (numerous sensors)

\end{itemize}

\end{description}

\end{itemize}

Konstantin drew the inspiration to use Android instead of Swing as a
context for teaching these topics from the mobile computing session at
\href{http://www.sigcse.org/sigcse2012}{SIGCSE 2012 in Raleigh}.

Furthermore, we have found the cost of switching from, say, Java Swing
to Android minimal. Besides, Android matters in the real world: it is
a widely used technology, and mobile app development skills are in
increasing demand.

While our overall goals are similar to those of the
\href{http://sofia.cs.vt.edu/sofia-2114/book}{Sofia framework project}, we
discuss here a language-based approach but are planning to enhance the
practice of Android development in Scala through additional support classes.

As mentioned above, current and future focus has been on these courses:
\begin{itemize}
\item {} 
\href{http://laufer.cs.luc.edu/teaching/313}{COMP 313/413: Intermediate Object-Oriented Development}
(focusing on software design and architecture), using Java with Android since fall 2012,
considering the addition of Scala down the road

\item {} 
\href{http://laufer.cs.luc.edu/teaching/473}{COMP 373/473: Advanced Object-Oriented Development},   using Scala since spring 2010, planning to add Android in spring 2014

\end{itemize}


\subsection{Tools}
\label{android:tools}
There are two sbt plugins for developing Android:
\begin{itemize}
\item {} 
\href{https://github.com/pfn/android-sdk-plugin}{https://github.com/pfn/android-sdk-plugin}

\item {} 
\href{http://fxthomas.github.io/android-plugin}{http://fxthomas.github.io/android-plugin}

\end{itemize}

The rapidly evolving topic of developing Android apps in Scala is the
subject of this discussion forum:
\begin{itemize}
\item {} 
\href{https://groups.google.com/forum/\#!topic/scala-on-android}{https://groups.google.com/forum/\#!topic/scala-on-android}

\end{itemize}

After some experimentation, we have found \href{https://github.com/pfn/android-sdk-plugin}{pfn's plugin} to be easier to use and
have adopted it for our Scala-based Android development.


\subsection{Examples}
\label{android:examples}
The learning objectives of each example are stated in the example's
readme.
\begin{itemize}
\item {} 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/clickcounter-android-scala}{Clickcounter app}

\item {} 
\href{https://bitbucket.org/loyolachicagocs\_plsystems/primenumbers-android-scala}{Prime checker app}

\item {} 
\href{https://bitbucket.org/loyolachicagocs\_distributed/primenumbers-spray-scala}{Prime checker web service}

\end{itemize}


\subsection{Lab Assignment}
\label{android:lab-assignment}\begin{description}
\item[{Format}] \leavevmode
Pair project

\item[{Time}] \leavevmode
10 minutes

\item[{Deliverable}] \leavevmode
An enhancement of \href{https://bitbucket.org/loyolachicagocs\_plsystems/clickcounter-android-scala}{this clickcounter app}
that addresses at least one following additional functional requirements:
\begin{itemize}
\item {} 
New user story: a max (\textasciicircum{}) button as the analogous dual to the
reset (0) button.

\item {} 
Retaining application state during rotation (\href{http://stackoverflow.com/questions/3916096/android-avd-rotate-portrait-landscape-how}{see here to find out how to rotate the emulator}).

\end{itemize}

\item[{Nonfunctional requirements}] \leavevmode\begin{itemize}
\item {} 
You should update the tests and the rest of the existing code accordingly.

\item {} 
You should implement the
\code{onSaveInstanceState} and \code{onRestoreInstanceState}
application lifecycle methods
(\href{http://developer.android.com/guide/components/activities.html\#SavingActivityState}{see}
for details. The system passes this method a Bundle in which
you can save state information about the activity as name-value
pairs, using methods such as \code{putString()} and \code{putInt()}.

\end{itemize}

\end{description}


\section{Basic Parallelism using Par}
\label{parallel:basic-parallelism-using-par}\label{parallel::doc}
Using parallelism solves problems more quickly than using a
single-processor machine, as is the case where groups of people solve
problems larger than one person can solve. But just as with groups of
people, there are additional costs and problems involved in coordinating
parallel processors:
\begin{itemize}
\item {} 
We need to have more than one processor work on the problem at the same
time. Our machine must have more than one processor, and the operating
system must be able to give more than one processor to our program at the
same time. Kernel threads allow this in Java. An alternative approach is to
have several networked computers work on parts of the problem; this is
discussed in Chapters 11 and 12, “Networking” and “Coordination.” of the
HPJPC book by Christopher and Thiruvathukal.

\item {} 
We need to assign parts of the problem to threads. This at least requires
rewriting a sequential program. It usually requires rethinking the
algorithm as well.

\item {} 
We need to coordinate the threads so they perform their operations in the
proper order, as well as avoid race conditions and deadlocks. A number of
useful facilities are not provided by the standard Java language package.
We provide a good collection for your use in our thread package.

\item {} 
We need to maintain a reasonable grain size. Grain size refers to the
amount of work a thread does between communications or synchronizations.
Fine grain uses very few instructions between synchronizations; coarse
grain uses a large amount of work. Too fine a grain wastes too much
overhead creating and synchronizing threads. Too coarse a grain results in
load imbalance and the underutilization of processors.

\end{itemize}

Two easy, practical approaches to dividing the work among several
processors are executing functions in parallel and executing
iterations of loops in parallel. Parallelizing loops will be presented
in the next chapter. In this chapter we will discuss running subroutines
in parallel.

Executing functions in parallel is an easy way to speed up
computation. The chunks of code are already packaged for you in methods;
you merely need to wrap runnable classes around them. Of course, there
are certain requirements:
\begin{itemize}
\item {} 
The function must be able to run in parallel with some other
computation. This usually means that there are several function
calls that can run independently.

\item {} 
The function must have a reasonable grain size. It costs a lot to
get a thread running, and it doesn’t pay off for only a few
instructions.

\end{itemize}

Two kinds of algorithms particularly adaptable to parallel execution of
functions are the divide-and-conquer and branch-and-bound algorithms.
Divide-and-conquer algorithms break large problems into parts and solve
the parts independently. Parts that are small enough are solved simply
as special cases. You must know how to break a large problem into parts
that can be solved independently and whose solutions can be reassembled
into a solution of the overall problem. The algorithm may undergo some
cost in breaking the problem into subparts or in assembling the
solutions.


\subsection{Example: Trapezoidal Numeric Integration}
\label{parallel:example-trapezoidal-numeric-integration}
Sometimes, a program needs to integrate a function (i.e., calculate the
area under a curve). It might be able to use a formula for the integral,
but doing so isn’t always convenient, or even possible. An easy
alternative approach is to approximate the curve with straight line
segments and calculate an estimate of the area from them.

This visual (courtesy of HPJPC) shows the trapezoidal method:

{\hfill\includegraphics{trapezoids.png}\hfill}

This equation shows how to calculate the area.

We wish to find the area under the curve from $a$ to $b$. We
approximate the function by dividing the domain from $a$ to $b$
into $g$ equally sized segments. Each segment is $(b - a) / g$
long. Let the boundaries of these segments be $x_0 = a$, $x_1$,
$x_1$, ... , $x_g = b$. The polyline approximating the curve will
have coordinates $(x_0, f(x_0))$,  $(x_1, f(x_1))$, $(x_2,
f(x_2))$, ..., $(x_g, f(x_g))$.

The area is then given by this formula, which sums the area of all trapezoids:

{\hfill\includegraphics{math1.png}\hfill}

If we apply that formula unthinkingly, we will evaluate the function twice for
each value of x, except the first and the last values. While the correct
result would be obtained, it is inefficient and kind of defeats the purpose of
going parallel. A little manipulation gives us the following:

{\hfill\includegraphics{math2.png}\hfill}

We've now reduced the problem to computing the parallel sum term, which is
represented nicely in Scala.

We present three solutions in Scala:
\begin{itemize}
\item {} 
\code{integrateSequential()}: The sequential (i.e. not parallel) solution is aimed at showcasing one of
the key benefits of functional programming in general. In many cases, the code closely follows the mathematics
you write. Because the code is clear in terms of its intentions, we can adapt the solution for parallel
execution.

\item {} 
\code{integrateParallel()}: The parallel version shows how to get parallel speedup in Scala from the
sequential one, simply by adding \code{par}.

\item {} \begin{description}
\item[{\code{integrateParallelGranular()}: This version shows how to combine parallel and serial execution. By}] \leavevmode
allowing the user to specify the grain size (number of retangles to do sequentially at a time),
it is possible to determine how Scala itself might be chunking the work in the \code{integrateParallel()}
solution.

\end{description}

\end{itemize}


\subsection{Download the Code}
\label{parallel:download-the-code}\begin{description}
\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} ZIP File}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/get/default.zip}{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/get/default.zip}

\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} via Mercurial}] \leavevmode
hg clone \href{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala}

\item[{\raisebox{-0.5\height}{\includegraphics{instructions.png}} Build and Run Instructions}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/overview}{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/overview}

\end{description}


\subsection{Going Scala!}
\label{parallel:going-scala}
Let's start by looking at \code{integrateSequential()}.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{def} \PYG{n}{integrateSequential}\PYG{o}{(}\PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{rectangles}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Fx}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{o}{\PYGZob{}}
    \PYG{k}{val} \PYG{n}{interval} \PYG{k}{=} \PYG{o}{(}\PYG{n}{b} \PYG{o}{\PYGZhy{}} \PYG{n}{a}\PYG{o}{)} \PYG{o}{/} \PYG{n}{rectangles}
    \PYG{k}{val} \PYG{n}{fxValues} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mi}{1} \PYG{n}{until} \PYG{n}{rectangles}\PYG{o}{)}\PYG{o}{.}\PYG{n}{view} \PYG{n}{map} \PYG{o}{\PYGZob{}} \PYG{n}{n} \PYG{k}{=\PYGZgt{}} \PYG{n}{f}\PYG{o}{(}\PYG{n}{a} \PYG{o}{+} \PYG{n}{n} \PYG{o}{*} \PYG{n}{interval}\PYG{o}{)} \PYG{o}{\PYGZcb{}}
    \PYG{n}{interval} \PYG{o}{*} \PYG{o}{(}\PYG{n}{f}\PYG{o}{(}\PYG{n}{a}\PYG{o}{)} \PYG{o}{/} \PYG{l+m+mi}{2} \PYG{o}{+} \PYG{n}{f}\PYG{o}{(}\PYG{n}{b}\PYG{o}{)} \PYG{o}{/} \PYG{l+m+mi}{2} \PYG{o}{+} \PYG{n}{fxValues}\PYG{o}{.}\PYG{n}{sum}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

As would be expected, we should be write this the way we think of the problem mathematically:
\begin{itemize}
\item {} 
\code{a} and \code{b}: The endpoints of the integration interval

\item {} 
\code{rectangles}: The number of rectangles to use to approximate the integral

\item {} 
\code{f}: The function to be integrated.

\end{itemize}

In the last case, this is where Scala makes our work particularly easy by allowing us to
define a proper function type as shown below:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{type} \PYG{k+kt}{Fx} \PYG{o}{=} \PYG{n+nc}{Double} \PYG{k}{=\PYGZgt{}} \PYG{n+nc}{Double}
\end{Verbatim}

In our previous Java work (in the book), we had to use Java \emph{interfaces} for
this same task. While seemingly just \emph{syntactic sugar}, Java's boilerplate is
offputting to computational scientists, who would rather use C and FORTRAN
where function parameters are possible. Unlike those choices, however, Scala
gives us the compelling aspect of \emph{full type checking}, which means that we
can be assured of excellent performance without the complexity--and sometimes
unsafe behavior--that is found in other languages.

Because it is essential to understand the sequential version (the core
algorithm) before proceeding, we offer a brief  explanation of each line of
code, even when obvious, and how we are taking advantage of Scala (when less
obvious!)
\begin{itemize}
\item {} 
In line 2, we calculate \code{interval} using the formula that was presented
earlier. Scala, being pragmatic, is able to do the right thing and treat the
entire expression as Double, resulting in a Double value. Scala really shines
here by not requiring us to declare every val type, owing to its innate type
inferencing mechanism. This results in code that is much easier to comprehend
(at least we like to think so).

\item {} 
In line 3, this requires a bit more explanation. Working from our equation,
recall that our summation term goes from 1 to the number of rectangles minus
0. We use Scala's until to get the indices. When \code{rectangles} is small, this
is fine. What happens when it is large? The answer depends on whether we are
using eager or lazy evaluation. In mathematical/scientific computing, we often
need to do a large number of iterations to get a better answer. This is where
the \code{view} comes in. It gives us a lazy sequence that can then be mapped
(also lazily) using the user-supplied function, \code{f}.

\item {} 
In line 4, we are able to plug everything into the derived formular for
calculating the trapezoidal integration. Technically, we could have put the
\code{fxValues} val definition in the same line of code, but having it separate
makes it easier to  understand for new Scala users (one of the goals for our
SIGCSE workshop). More importantly, you should be able to write the code this
way and not have to worry about losing performance. By setting up this lazy
computation, we're able to compute the sum \emph{on demand}. Aside from this split,
the code here exactly matches the formula we derived for performing
trapezoidal integration.

\end{itemize}

The sequential version of integration presented here is completely side-effect
free. That is, all of the work is being done without mutating state. This
means that it can immmediately be turned into something parallel in Scala,
provided we know where the actual work is being done. Let's continue this
exploration!


\subsection{Going Parallel}
\label{parallel:going-parallel}
The immediately preceding discussion was presented with great care, because
what we are about to demonstrate illustrates how one needs to do very little
work to take what is sometimes known as an \emph{embarrassingly parallel} algorithm
and make it run in parallel. The term \emph{embarrassing} is a tad misleading. As
we'll see, the results don't always follow your intuition. Furthermore, while
the results can be gotten quickly, it doesn't always mean that you are getting
the best results possible. For example, as well as Scala does, it still
doesn't do nearly as well as our hand-coded multithreaded Java example from
HPJPC. We'll say more about this later.

Let's look at the parallel version.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{def} \PYG{n}{integrateParallel}\PYG{o}{(}\PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{rectangles}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Fx}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{o}{\PYGZob{}}
    \PYG{k}{val} \PYG{n}{interval} \PYG{k}{=} \PYG{o}{(}\PYG{n}{b} \PYG{o}{\PYGZhy{}} \PYG{n}{a}\PYG{o}{)} \PYG{o}{/} \PYG{n}{rectangles}
    \PYG{k}{val} \PYG{n}{fxValues} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mi}{1} \PYG{n}{until} \PYG{n}{rectangles}\PYG{o}{)}\PYG{o}{.}\PYG{n}{par}\PYG{o}{.}\PYG{n}{view} \PYG{n}{map} \PYG{o}{\PYGZob{}} \PYG{n}{n} \PYG{k}{=\PYGZgt{}} \PYG{n}{f}\PYG{o}{(}\PYG{n}{a} \PYG{o}{+} \PYG{n}{n} \PYG{o}{*} \PYG{n}{interval}\PYG{o}{)} \PYG{o}{\PYGZcb{}}
    \PYG{n}{interval} \PYG{o}{*} \PYG{o}{(}\PYG{n}{f}\PYG{o}{(}\PYG{n}{a}\PYG{o}{)} \PYG{o}{/} \PYG{l+m+mi}{2} \PYG{o}{+} \PYG{n}{f}\PYG{o}{(}\PYG{n}{b}\PYG{o}{)} \PYG{o}{/} \PYG{l+m+mi}{2} \PYG{o}{+} \PYG{n}{fxValues}\PYG{o}{.}\PYG{n}{sum}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

In this version, observe that we have added the \code{par} method call just
before generating the lazy \code{view}. This is the only sensible place to add
\code{par}, because in mathematical/scientific computing, we know that most of
the parallel potential is found \emph{where the loops are}. The \code{1 until
rectangles} is where the actual workload is being generated, so it is a
natural place to suggest \code{par}.


\subsection{Testing}
\label{parallel:testing}
The following code shows the unit tests for our various \emph{integration} examples.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{package} \PYG{n+nn}{edu.luc.etl.sigcse13.scala.integration}

\PYG{k}{import} \PYG{n+nn}{org.junit.Test}
\PYG{k}{import} \PYG{n+nn}{org.junit.Assert.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{Integration.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{Fixtures.\PYGZus{}}

\PYG{c+cm}{/*}\PYG{c+cm}{*}
\PYG{c+cm}{ }\PYG{c+cm}{*}\PYG{c+cm}{ Simple JUnit\PYGZhy{}based tests.}
\PYG{c+cm}{ }\PYG{c+cm}{*/}
\PYG{k}{class} \PYG{n+nc}{Tests} \PYG{o}{\PYGZob{}}

  \PYG{n+nd}{@Test} \PYG{k}{def} \PYG{n}{testSequential}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mf}{333.3}\PYG{o}{,} \PYG{n}{integrateSequential}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{l+m+mi}{1000}\PYG{o}{,} \PYG{n}{sqr}\PYG{o}{)}\PYG{o}{,} \PYG{l+m+mf}{0.1}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}

  \PYG{n+nd}{@Test} \PYG{k}{def} \PYG{n}{testParallel}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mf}{333.3}\PYG{o}{,} \PYG{n}{integrateParallel}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{l+m+mi}{1000}\PYG{o}{,} \PYG{n}{sqr}\PYG{o}{)}\PYG{o}{,} \PYG{l+m+mf}{0.1}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}

  \PYG{n+nd}{@Test} \PYG{k}{def} \PYG{n}{testParallelGranular}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mf}{333.3}\PYG{o}{,} \PYG{n}{integrateParallelGranular}\PYG{o}{(}\PYG{l+m+mi}{10}\PYG{o}{)}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{l+m+mi}{1000}\PYG{o}{,} \PYG{n}{sqr}\PYG{o}{)}\PYG{o}{,} \PYG{l+m+mf}{0.1}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

For the purpose of testing, we set up $f(x) = x^2$ and integrated it
from 0 to 10. The value of this integral should be 333.333333333....

We can't stress enough the importance of unit tests, especially when working a
sequential algorithm into a parallel one. While you are less likely to make
mistakes in Scala, it is very easy when trying certain strategies to get the
wrong answer. (In fact, one of them, the third, gave an incorrect answer
during testing, simply because of a division error I made when computing the
number of workers!)

Using the notion of a test fixture, it is possible to specify what function we
wish to test without contaminating the general-purpose code we wrote with a
specific function to be integrated. See below.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{package} \PYG{n+nn}{edu.luc.etl.sigcse13.scala.integration}

\PYG{c+c1}{// begin\PYGZhy{}object\PYGZhy{}Fixtures}
\PYG{k}{object} \PYG{n+nc}{Fixtures} \PYG{o}{\PYGZob{}}
  \PYG{k}{def} \PYG{n}{sqr}\PYG{o}{(}\PYG{n}{x}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{n}{x} \PYG{o}{*} \PYG{n}{x}
\PYG{o}{\PYGZcb{}}
\PYG{c+c1}{// end\PYGZhy{}object\PYGZhy{}Fixtures}
\end{Verbatim}


\subsection{Running}
\label{parallel:running}
The tradition of scientific computing is one where users \emph{want} and \emph{need} to
be able to run it from the command-line, often in an unattended fashion (say,
on a computing cluster or network of workstations or cloud resources). The
following is the main program we put together to run the integration of
$f(x) = x^2$ manually. You can specify the number of rectangles, the
number of times to run each of the experiments, and a grain size for testing
the combined parallel/sequential version, \code{integrateParallelGranular()}.
We'll say more about this function in our performance discussion.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{package} \PYG{n+nn}{edu.luc.etl.sigcse13.scala.integration}

\PYG{k}{import} \PYG{n+nn}{Integration.\PYGZus{}}
\PYG{k}{import} \PYG{n+nn}{Fixtures.sqr}

\PYG{k}{object} \PYG{n+nc}{Main} \PYG{k}{extends} \PYG{o}{\PYGZob{}}

  \PYG{k}{def} \PYG{n}{main}\PYG{o}{(}\PYG{n}{args}\PYG{k}{:} \PYG{k+kt}{Array}\PYG{o}{[}\PYG{k+kt}{String}\PYG{o}{]}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{k}{try} \PYG{o}{\PYGZob{}}
      \PYG{n}{require} \PYG{o}{\PYGZob{}} \PYG{l+m+mi}{2} \PYG{o}{\PYGZlt{}=} \PYG{n}{args}\PYG{o}{.}\PYG{n}{length} \PYG{o}{\PYGZcb{}}
      \PYG{k}{val} \PYG{n}{rectangles} \PYG{k}{=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{max}\PYG{o}{(}\PYG{n}{args}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toInt}\PYG{o}{,} \PYG{l+m+mi}{1000}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{n} \PYG{k}{=} \PYG{n}{math}\PYG{o}{.}\PYG{n}{max}\PYG{o}{(}\PYG{n}{args}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toInt}\PYG{o}{,} \PYG{l+m+mi}{1}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{grainSize} \PYG{k}{=} \PYG{k}{if} \PYG{o}{(}\PYG{n}{args}\PYG{o}{.}\PYG{n}{length} \PYG{o}{==} \PYG{l+m+mi}{3}\PYG{o}{)} \PYG{n}{math}\PYG{o}{.}\PYG{n}{min}\PYG{o}{(}\PYG{n}{args}\PYG{o}{(}\PYG{l+m+mi}{2}\PYG{o}{)}\PYG{o}{.}\PYG{n}{toInt}\PYG{o}{,} \PYG{n}{rectangles}\PYG{o}{)} \PYG{k}{else} \PYG{n}{rectangles}

      \PYG{n}{timedRun}\PYG{o}{(}\PYG{n}{rectangles}\PYG{o}{,} \PYG{n}{n}\PYG{o}{,} \PYG{l+s}{\PYGZdq{}sequentially\PYGZdq{}}\PYG{o}{,} \PYG{n}{integrateSequential}\PYG{o}{)}
      \PYG{n}{timedRun}\PYG{o}{(}\PYG{n}{rectangles}\PYG{o}{,} \PYG{n}{n}\PYG{o}{,} \PYG{l+s}{\PYGZdq{}in parallel\PYGZdq{}}\PYG{o}{,} \PYG{n}{integrateParallel}\PYG{o}{)}
      \PYG{n}{timedRun}\PYG{o}{(}\PYG{n}{rectangles}\PYG{o}{,} \PYG{n}{n}\PYG{o}{,} \PYG{l+s}{\PYGZdq{}in parallel with \PYGZdq{}} \PYG{o}{+} \PYG{n}{grainSize} \PYG{o}{+}
        \PYG{l+s}{\PYGZdq{} rectangles per serial worker\PYGZdq{}}\PYG{o}{,} \PYG{n}{integrateParallelGranular}\PYG{o}{(}\PYG{n}{grainSize}\PYG{o}{)}\PYG{o}{)}

    \PYG{o}{\PYGZcb{}} \PYG{k}{catch} \PYG{o}{\PYGZob{}}
      \PYG{k}{case} \PYG{k}{\PYGZus{}}\PYG{k}{:} \PYG{k+kt}{NumberFormatException}    \PYG{o}{=\PYGZgt{}} \PYG{n}{usage}\PYG{o}{(}\PYG{o}{)}
      \PYG{k}{case} \PYG{k}{\PYGZus{}}\PYG{k}{:} \PYG{k+kt}{IllegalArgumentException} \PYG{o}{=\PYGZgt{}} \PYG{n}{usage}\PYG{o}{(}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
  \PYG{o}{\PYGZcb{}}

  \PYG{k}{def} \PYG{n}{usage}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n+nc}{Console}\PYG{o}{.}\PYG{n}{err}\PYG{o}{.}\PYG{n}{println}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}usage: rectangles (\PYGZgt{}= 1000) \PYGZdq{}} \PYG{o}{+}
      \PYG{l+s}{\PYGZdq{}numberOfRuns (\PYGZgt{}= 1) [ grainSize (rectangles \PYGZpc{} grainSize == 0) ]\PYGZdq{}}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}

  \PYG{k}{def} \PYG{n}{timeThis}\PYG{o}{[}\PYG{k+kt}{A}\PYG{o}{]}\PYG{o}{(}\PYG{n}{s}\PYG{k}{:} \PYG{k+kt}{String}\PYG{o}{)}\PYG{o}{(}\PYG{n}{block}\PYG{k}{:} \PYG{o}{=\PYGZgt{}} \PYG{n}{A}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{A} \PYG{o}{=} \PYG{o}{\PYGZob{}}
    \PYG{k}{val} \PYG{n}{time0} \PYG{k}{=} \PYG{n+nc}{System}\PYG{o}{.}\PYG{n}{currentTimeMillis}
    \PYG{k}{val} \PYG{n}{b} \PYG{k}{=} \PYG{n}{block}
    \PYG{k}{val} \PYG{n}{time1} \PYG{k}{=} \PYG{n+nc}{System}\PYG{o}{.}\PYG{n}{currentTimeMillis} \PYG{o}{\PYGZhy{}} \PYG{n}{time0}
    \PYG{n}{println}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Timing \PYGZdq{}} \PYG{o}{+} \PYG{n}{s} \PYG{o}{+} \PYG{l+s}{\PYGZdq{} = \PYGZdq{}} \PYG{o}{+} \PYG{n}{time1}\PYG{o}{)}
    \PYG{n}{b}
  \PYG{o}{\PYGZcb{}}

  \PYG{c+c1}{// begin\PYGZhy{}timedRun}
  \PYG{k}{def} \PYG{n}{timedRun}\PYG{o}{(}\PYG{n}{rectangles}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{how}\PYG{k}{:} \PYG{k+kt}{String}\PYG{o}{,}
    \PYG{n}{integrationStrategy}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Double}\PYG{o}{,} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n+nc}{Int}\PYG{o}{,} \PYG{n+nc}{Fx}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n+nc}{Double}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{timeThis}\PYG{o}{(}\PYG{n}{how}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{n}{print}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Computing area \PYGZdq{}} \PYG{o}{+} \PYG{n}{how} \PYG{o}{+} \PYG{l+s}{\PYGZdq{}; now timing \PYGZdq{}} \PYG{o}{+} \PYG{n}{n} \PYG{o}{+} \PYG{l+s}{\PYGZdq{} iterations\PYGZdq{}}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{area}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{o}{(}\PYG{l+m+mi}{1} \PYG{n}{to} \PYG{n}{n}\PYG{o}{)}\PYG{o}{.}\PYG{n}{map} \PYG{o}{\PYGZob{}} \PYG{k}{\PYGZus{}} \PYG{k}{=\PYGZgt{}} \PYG{n}{integrationStrategy}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{,} \PYG{l+m+mi}{10}\PYG{o}{,} \PYG{n}{rectangles}\PYG{o}{,} \PYG{n}{sqr}\PYG{o}{)} \PYG{o}{\PYGZcb{}}\PYG{o}{.}\PYG{n}{head}
      \PYG{n}{println}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}; area = \PYGZdq{}} \PYG{o}{+} \PYG{n}{area}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
  \PYG{o}{\PYGZcb{}}
  \PYG{c+c1}{// end\PYGZhy{}timedRun}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}


\subsection{Initial Experiments with Performance}
\label{parallel:initial-experiments-with-performance}
This is still being written up but will be demonstrated live.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{def} \PYG{n}{integrateParallelGranular}\PYG{o}{(}\PYG{n}{grainSize}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{o}{(}\PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{b}\PYG{k}{:} \PYG{k+kt}{Double}\PYG{o}{,} \PYG{n}{rectangles}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Fx}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Double} \PYG{o}{=} \PYG{o}{\PYGZob{}}
    \PYG{n}{require} \PYG{o}{\PYGZob{}} \PYG{n}{rectangles} \PYG{o}{\PYGZpc{}} \PYG{n}{grainSize} \PYG{o}{==} \PYG{l+m+mi}{0} \PYG{o}{\PYGZcb{}} \PYG{c+c1}{// can relax this later}
    \PYG{k}{val} \PYG{n}{workers} \PYG{k}{=} \PYG{n}{rectangles} \PYG{o}{/} \PYG{n}{grainSize}
    \PYG{k}{val} \PYG{n}{interval} \PYG{k}{=} \PYG{o}{(}\PYG{n}{b} \PYG{o}{\PYGZhy{}} \PYG{n}{a}\PYG{o}{)} \PYG{o}{/} \PYG{n}{workers}
    \PYG{k}{val} \PYG{n}{fullIntegration} \PYG{k}{=} \PYG{o}{(}\PYG{l+m+mi}{0} \PYG{n}{until} \PYG{n}{workers}\PYG{o}{)}\PYG{o}{.}\PYG{n}{par}\PYG{o}{.}\PYG{n}{view} \PYG{n}{map} \PYG{o}{\PYGZob{}} \PYG{n}{n} \PYG{k}{=\PYGZgt{}}
      \PYG{k}{val} \PYG{n}{c} \PYG{k}{=} \PYG{n}{a} \PYG{o}{+} \PYG{n}{n} \PYG{o}{*} \PYG{n}{interval}
      \PYG{n}{integrateSequential}\PYG{o}{(}\PYG{n}{c}\PYG{o}{,} \PYG{n}{c} \PYG{o}{+} \PYG{n}{interval}\PYG{o}{,} \PYG{n}{grainSize}\PYG{o}{,} \PYG{n}{f}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
    \PYG{n}{fullIntegration}\PYG{o}{.}\PYG{n}{sum}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}


\subsection{Previous Work}
\label{parallel:previous-work}
This example was developed as part of High-Performance Java Platform Computing
by Thomas W. Christopher and George K. Thiruvathukal.
\begin{description}
\item[{\raisebox{-0.5\height}{\includegraphics{pdf.png}} PDF of Book}] \leavevmode
\href{https://hpjpc.googlecode.com/files/HPJPC\%20Christopher\%20and\%20Thiruvathukal.pdf}{https://hpjpc.googlecode.com/files/HPJPC\%20Christopher\%20and\%20Thiruvathukal.pdf}

\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} ZIP File}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java/get/default.zip}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java/get/default.zip}

\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} via Mercurial}] \leavevmode
hg clone \href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}

\item[{\raisebox{-0.5\height}{\includegraphics{instructions.png}} Build and Run Instructions}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/overview}{https://bitbucket.org/loyolachicagocs\_plsystems/integration-scala/overview}

\end{description}

\index{parallelism!actors}\index{actors!parallelism}

\section{Parallelism using Actors}
\label{actors:actors}\label{actors:index-0}\label{actors::doc}\label{actors:parallelism-using-actors}
In this section, we're going to take a look at the Java vs. Scala  way of
doing things. We'll look at a guiding example that is focused on
concurrent/parallel computing. This example appeared in \emph{High Performance Java
Platform Computing} by Thomas W. Christopher and George K. Thiruvathukal.
We'll show how to organize a previously worked out solution that uses more
explicit concurrency mechanisms from Java and how it can be reworked into a
side-effect free Scala version by taking advantage of Scala's innate support
for basic actor-style parallelism.

\index{algorithm!Longest Common Subsequence}\index{Longest Common Subsequence!algorithm}

\subsection{Guiding Example: Longest Common Subsequence}
\label{actors:guiding-example-longest-common-subsequence}\label{actors:lcs}\label{actors:index-1}
A longest common subsequence (LCS) of two strings is a longest sequence of
characters that occurs in order in the two strings. It differs from the
\emph{longest common} substring in that the characters in the longest common
subsequence need not be contiguous. There may, of course, be more than one
LCS, since there may be several subsequences with the same length.

There is a folk algorithm to find the \emph{length} of the LCS of two strings. The
algorithm uses a form of dynamic programming. In divide-and-conquer
algorithms, recall that the overall problem is broken into parts, the parts
are solved individually, and the solutions are assembled into a solution to
the overall problem. Dynamic programming is similar, except that the best way
to divide the overall problem into parts is not known before the subproblems
are solved, so dynamic programming solves all subproblems and then finds the
best way to assemble them.

The algorithm works as follows: Let the two strings be \code{c0} and \code{c1}.
Create a two-dimensional array \code{a}:

\begin{Verbatim}[commandchars=\\\{\}]
int [][] a=new int[c0.length()+1] [c1.length()+1]
\end{Verbatim}

Initialize \code{a{[}i{]}{[}0{]}} to 0 for all \code{i} and \code{a{[}0{]}{[}j{]}} to 0 for all \code{j},
since there are no characters in an empty substring. The other elements,
\code{a{[}i{]}{[}j{]}} , are filled in as follows:

\begin{Verbatim}[commandchars=\\\{\}]
for (int i=0; i \textless{}= c0.length(); i++)
   a[i][0] = 0;

for (int j=0; j \textless{}= c1.length(); j++)
   a[0][j] = 0;
\end{Verbatim}

We will fill in the array so that \code{a{[}i{]}{[}j{]}} is the length of the LCS of
\code{c0.substring(0,i)} and \code{c1.substring(0,j)}. Recall that
\code{s.substring(m,n)} is the substring of \code{s} from position \code{m} up to, but
not including, position \code{n}.:

\begin{Verbatim}[commandchars=\\\{\}]
for (i=1; i \textless{}= c0.length(); i++)
   for (j=1; j \textless{}= c1.length(); j++)
      if (c0.charAt(i-1) == c1.charAt(j-1))
         a[i][j]=a[i-1][j-1]+1;
      else
         a[i][j]=Math.max(a[i][j-1],a[i-1][j]);
\end{Verbatim}

The above shows a \emph{traditional} imperative solution that constructs a result
matrix comprising the results of the LCS.

So how exactly does this method work?

Element \code{a{[}i-1{]}{[}j-1{]}} has the length of the LCS of string
\code{c0.substring(0,i-1)} and \code{c1.substring(0,j-1)}. If elements
c0.charAt(i-1) and c1.charAt(j-1) are found to be equal, then the LCS can be
extended by one to length \code{a{[}i-1{]} {[}j-1{]}+1}. If these characters don’t match,
then what? In that case, we ignore the last character in one or the other of
the strings. The LCS is either \code{a{[}i{]}{[}j-1{]}} or \code{a{[}i-1{]}{[}j{]}}, representing
the maximum length of the LCS for all but the last character of
\code{c1.substring(0,j-1)} or \code{c0.substring(0,i-1)}, respectively.

The chore graph from {\hyperref[actors:hpjpc]{{[}HPJPC{]}}} for calculation of the LCS is shown in the following figure.

{\hfill\includegraphics{lcs-systolic.png}\hfill}

Any order of calculation that is consistent with the dependencies is
permissible. Two are fairly obvious: (1) by rows, top to bottom, and (2) by
columns, left to right.

Another possibility is along diagonals. All \code{a{[}i{]}{[}j{]}}, where \code{i+j==m} can
be  calculated at the same time, for \code{m} stepping from 2 to
\code{c0.length()+c1.length()}. . Visualizing waves of computation passing across
arrays is a good technique for designing parallel array algorithms. It has
been researched under the names systolic arrays and wavefront arrays
{\hyperref[actors:wavefront]{{[}Wavefront{]}}}.

The following figure shows how a wavefront computation progresses.

{\hfill\includegraphics{lcs-wavefront.png}\hfill}

\index{concurrency!explicit}\index{explicit!concurrency}\index{parallelism!explicit}\index{explicit!parallelism}

\subsection{Java Threads Implementation}
\label{actors:java-threads-implementation}\label{actors:index-2}\begin{description}
\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} ZIP File}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java/get/default.zip}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java/get/default.zip}

\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} via Mercurial}] \leavevmode
hg clone \href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}

\item[{\raisebox{-0.5\height}{\includegraphics{instructions.png}} Build and Run Instructions}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}{https://bitbucket.org/loyolachicagocs\_books/hpjpc-source-java}

\end{description}

Our Java implementation (see \href{http://bit.ly/HPJPC-LCS}{LCS.java})  of the
LCS algorithm divides the array into vertical bands and is pictured in Each
band is filled in row by row from top to bottom. Each band (except the
leftmost)  must wait for the band to its left to fill in the last element of a
row before it can start can start filling in that row. This is an instance of
the producer-consumer releationship.

The following figure shows how our Java solution organizes the work in bands:

{\hfill\includegraphics{lcs-bands.png}\hfill}

LCS class

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
   \PYG{k+kt}{int} \PYG{n}{numThreads}\PYG{o}{;}
   \PYG{k+kt}{char}\PYG{o}{[}\PYG{o}{]} \PYG{n}{c0}\PYG{o}{;}
   \PYG{k+kt}{char}\PYG{o}{[}\PYG{o}{]} \PYG{n}{c1}\PYG{o}{;}
   \PYG{k+kt}{int}\PYG{o}{[}\PYG{o}{]}\PYG{o}{[}\PYG{o}{]} \PYG{n}{a}\PYG{o}{;}
   \PYG{n}{Accumulator} \PYG{n}{done}\PYG{o}{;}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
   \PYG{k+kd}{public} \PYG{n+nf}{LCS}\PYG{o}{(}\PYG{k+kt}{char}\PYG{o}{[}\PYG{o}{]} \PYG{n}{c0}\PYG{o}{,} \PYG{k+kt}{char}\PYG{o}{[}\PYG{o}{]} \PYG{n}{c1}\PYG{o}{,} \PYG{k+kt}{int} \PYG{n}{numThreads}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{numThreads} \PYG{o}{=} \PYG{n}{numThreads}\PYG{o}{;}
      \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{c0} \PYG{o}{=} \PYG{n}{c0}\PYG{o}{;}
      \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{c1} \PYG{o}{=} \PYG{n}{c1}\PYG{o}{;}
      \PYG{k+kt}{int} \PYG{n}{i}\PYG{o}{;}
      \PYG{n}{done} \PYG{o}{=} \PYG{k}{new} \PYG{n}{Accumulator}\PYG{o}{(}\PYG{n}{numThreads}\PYG{o}{)}\PYG{o}{;}

      \PYG{n}{a} \PYG{o}{=} \PYG{k}{new} \PYG{k+kt}{int}\PYG{o}{[}\PYG{n}{c0}\PYG{o}{.}\PYG{n+na}{length} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{[}\PYG{n}{c1}\PYG{o}{.}\PYG{n+na}{length} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{;}

      \PYG{n}{Semaphore} \PYG{n}{left} \PYG{o}{=} \PYG{k}{new} \PYG{n}{Semaphore}\PYG{o}{(}\PYG{n}{c0}\PYG{o}{.}\PYG{n+na}{length}\PYG{o}{)}\PYG{o}{,} \PYG{n}{right}\PYG{o}{;}
      \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{0}\PYG{o}{;} \PYG{n}{i} \PYG{o}{\PYGZlt{}} \PYG{n}{numThreads}\PYG{o}{;} \PYG{n}{i}\PYG{o}{+}\PYG{o}{+}\PYG{o}{)} \PYG{o}{\PYGZob{}}
         \PYG{n}{right} \PYG{o}{=} \PYG{k}{new} \PYG{n}{Semaphore}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
         \PYG{k}{new} \PYG{n+nf}{Band}\PYG{o}{(}\PYG{n}{startOfBand}\PYG{o}{(}\PYG{n}{i}\PYG{o}{,} \PYG{n}{numThreads}\PYG{o}{,} \PYG{n}{c1}\PYG{o}{.}\PYG{n+na}{length}\PYG{o}{)}\PYG{o}{,} \PYG{n}{startOfBand}\PYG{o}{(}\PYG{n}{i} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{,}
               \PYG{n}{numThreads}\PYG{o}{,} \PYG{n}{c1}\PYG{o}{.}\PYG{n+na}{length}\PYG{o}{)} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{left}\PYG{o}{,} \PYG{n}{right}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{start}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
         \PYG{n}{left} \PYG{o}{=} \PYG{n}{right}\PYG{o}{;}
      \PYG{o}{\PYGZcb{}}
   \PYG{o}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
   \PYG{k+kd}{public} \PYG{n+nf}{LCS}\PYG{o}{(}\PYG{n}{String} \PYG{n}{s0}\PYG{o}{,} \PYG{n}{String} \PYG{n}{s1}\PYG{o}{,} \PYG{k+kt}{int} \PYG{n}{numThreads}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{this}\PYG{o}{(}\PYG{n}{s0}\PYG{o}{.}\PYG{n+na}{toCharArray}\PYG{o}{(}\PYG{o}{)}\PYG{o}{,} \PYG{n}{s1}\PYG{o}{.}\PYG{n+na}{toCharArray}\PYG{o}{(}\PYG{o}{)}\PYG{o}{,} \PYG{n}{numThreads}\PYG{o}{)}\PYG{o}{;}
   \PYG{o}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
   \PYG{k+kt}{int} \PYG{n+nf}{startOfBand}\PYG{o}{(}\PYG{k+kt}{int} \PYG{n}{i}\PYG{o}{,} \PYG{k+kt}{int} \PYG{n}{nb}\PYG{o}{,} \PYG{k+kt}{int} \PYG{n}{N}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{return} \PYG{l+m+mi}{1} \PYG{o}{+} \PYG{n}{i} \PYG{o}{*} \PYG{o}{(}\PYG{n}{N} \PYG{o}{/} \PYG{n}{nb}\PYG{o}{)} \PYG{o}{+} \PYG{n}{Math}\PYG{o}{.}\PYG{n+na}{min}\PYG{o}{(}\PYG{n}{i}\PYG{o}{,} \PYG{n}{N} \PYG{o}{\PYGZpc{}} \PYG{n}{nb}\PYG{o}{)}\PYG{o}{;}
   \PYG{o}{\PYGZcb{}}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
   \PYG{k+kd}{public} \PYG{k+kt}{int} \PYG{n+nf}{getLength}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{try} \PYG{o}{\PYGZob{}}
         \PYG{n}{done}\PYG{o}{.}\PYG{n+na}{getFuture}\PYG{o}{(}\PYG{o}{)}\PYG{o}{.}\PYG{n+na}{getValue}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
      \PYG{o}{\PYGZcb{}} \PYG{k}{catch} \PYG{o}{(}\PYG{n}{InterruptedException} \PYG{n}{ex}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{o}{\PYGZcb{}}
      \PYG{k}{return} \PYG{n}{a}\PYG{o}{[}\PYG{n}{c0}\PYG{o}{.}\PYG{n+na}{length}\PYG{o}{]}\PYG{o}{[}\PYG{n}{c1}\PYG{o}{.}\PYG{n+na}{length}\PYG{o}{]}\PYG{o}{;}
   \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Band internal class (does the work)

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k+kt}{int} \PYG{n}{low}\PYG{o}{;}
      \PYG{k+kt}{int} \PYG{n}{high}\PYG{o}{;}
      \PYG{n}{Semaphore} \PYG{n}{left}\PYG{o}{,} \PYG{n}{right}\PYG{o}{;}
\end{Verbatim}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{n}{Band}\PYG{o}{(}\PYG{k+kt}{int} \PYG{n}{low}\PYG{o}{,} \PYG{k+kt}{int} \PYG{n}{high}\PYG{o}{,} \PYG{n}{Semaphore} \PYG{n}{left}\PYG{o}{,} \PYG{n}{Semaphore} \PYG{n}{right}\PYG{o}{)} \PYG{o}{\PYGZob{}}
         \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{low} \PYG{o}{=} \PYG{n}{low}\PYG{o}{;}
         \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{high} \PYG{o}{=} \PYG{n}{high}\PYG{o}{;}
         \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{left} \PYG{o}{=} \PYG{n}{left}\PYG{o}{;}
         \PYG{k}{this}\PYG{o}{.}\PYG{n+na}{right} \PYG{o}{=} \PYG{n}{right}\PYG{o}{;}
      \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Actual Runnable body

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k+kd}{public} \PYG{k+kt}{void} \PYG{n+nf}{run}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
         \PYG{k}{try} \PYG{o}{\PYGZob{}}
            \PYG{k+kt}{int} \PYG{n}{i}\PYG{o}{,} \PYG{n}{j}\PYG{o}{;}
            \PYG{k}{for} \PYG{o}{(}\PYG{n}{i} \PYG{o}{=} \PYG{l+m+mi}{1}\PYG{o}{;} \PYG{n}{i} \PYG{o}{\PYGZlt{}} \PYG{n}{a}\PYG{o}{.}\PYG{n+na}{length}\PYG{o}{;} \PYG{n}{i}\PYG{o}{+}\PYG{o}{+}\PYG{o}{)} \PYG{o}{\PYGZob{}}
               \PYG{n}{left}\PYG{o}{.}\PYG{n+na}{down}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
               \PYG{k}{for} \PYG{o}{(}\PYG{n}{j} \PYG{o}{=} \PYG{n}{low}\PYG{o}{;} \PYG{n}{j} \PYG{o}{\PYGZlt{}}\PYG{o}{=} \PYG{n}{high}\PYG{o}{;} \PYG{n}{j}\PYG{o}{+}\PYG{o}{+}\PYG{o}{)} \PYG{o}{\PYGZob{}}
                  \PYG{k}{if} \PYG{o}{(}\PYG{n}{c0}\PYG{o}{[}\PYG{n}{i} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{]} \PYG{o}{=}\PYG{o}{=} \PYG{n}{c1}\PYG{o}{[}\PYG{n}{j} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{)}
                     \PYG{n}{a}\PYG{o}{[}\PYG{n}{i}\PYG{o}{]}\PYG{o}{[}\PYG{n}{j}\PYG{o}{]} \PYG{o}{=} \PYG{n}{a}\PYG{o}{[}\PYG{n}{i} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{[}\PYG{n}{j} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{]} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{;}
                  \PYG{k}{else}
                     \PYG{n}{a}\PYG{o}{[}\PYG{n}{i}\PYG{o}{]}\PYG{o}{[}\PYG{n}{j}\PYG{o}{]} \PYG{o}{=} \PYG{n}{Math}\PYG{o}{.}\PYG{n+na}{max}\PYG{o}{(}\PYG{n}{a}\PYG{o}{[}\PYG{n}{i} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{[}\PYG{n}{j}\PYG{o}{]}\PYG{o}{,} \PYG{n}{a}\PYG{o}{[}\PYG{n}{i}\PYG{o}{]}\PYG{o}{[}\PYG{n}{j} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{)}\PYG{o}{;}
               \PYG{o}{\PYGZcb{}}
               \PYG{n}{right}\PYG{o}{.}\PYG{n+na}{up}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
            \PYG{o}{\PYGZcb{}}
            \PYG{n}{done}\PYG{o}{.}\PYG{n+na}{signal}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
         \PYG{o}{\PYGZcb{}} \PYG{k}{catch} \PYG{o}{(}\PYG{n}{InterruptedException} \PYG{n}{ex}\PYG{o}{)} \PYG{o}{\PYGZob{}}
         \PYG{o}{\PYGZcb{}}
      \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Main

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
      \PYG{k+kd}{public} \PYG{k+kd}{static} \PYG{k+kt}{void} \PYG{n+nf}{main}\PYG{o}{(}\PYG{n}{String}\PYG{o}{[}\PYG{o}{]} \PYG{n}{args}\PYG{o}{)} \PYG{o}{\PYGZob{}}
         \PYG{k}{if} \PYG{o}{(}\PYG{n}{args}\PYG{o}{.}\PYG{n+na}{length} \PYG{o}{\PYGZlt{}} \PYG{l+m+mi}{2}\PYG{o}{)} \PYG{o}{\PYGZob{}}
            \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{out}\PYG{o}{.}\PYG{n+na}{println}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Usage: java LCS\PYGZdl{}Test1 string0 string1\PYGZdq{}}\PYG{o}{)}\PYG{o}{;}
            \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{exit}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{;}
         \PYG{o}{\PYGZcb{}}
         \PYG{k+kt}{int} \PYG{n}{nt} \PYG{o}{=} \PYG{l+m+mi}{3}\PYG{o}{;}
         \PYG{n}{String} \PYG{n}{s0} \PYG{o}{=} \PYG{n}{args}\PYG{o}{[}\PYG{l+m+mi}{0}\PYG{o}{]}\PYG{o}{;}
         \PYG{n}{String} \PYG{n}{s1} \PYG{o}{=} \PYG{n}{args}\PYG{o}{[}\PYG{l+m+mi}{1}\PYG{o}{]}\PYG{o}{;}
         \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{out}\PYG{o}{.}\PYG{n+na}{println}\PYG{o}{(}\PYG{n}{s0}\PYG{o}{)}\PYG{o}{;}
         \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{out}\PYG{o}{.}\PYG{n+na}{println}\PYG{o}{(}\PYG{n}{s1}\PYG{o}{)}\PYG{o}{;}
         \PYG{k+kt}{long} \PYG{n}{t0} \PYG{o}{=} \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{currentTimeMillis}\PYG{o}{(}\PYG{o}{)}\PYG{o}{;}
         \PYG{n}{LCS} \PYG{n}{w} \PYG{o}{=} \PYG{k}{new} \PYG{n}{LCS}\PYG{o}{(}\PYG{n}{s0}\PYG{o}{,} \PYG{n}{s1}\PYG{o}{,} \PYG{n}{nt}\PYG{o}{)}\PYG{o}{;}
         \PYG{k+kt}{long} \PYG{n}{t1} \PYG{o}{=} \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{currentTimeMillis}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZhy{}} \PYG{n}{t0}\PYG{o}{;}
         \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{out}\PYG{o}{.}\PYG{n+na}{println}\PYG{o}{(}\PYG{n}{w}\PYG{o}{.}\PYG{n+na}{getLength}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}\PYG{o}{;}
         \PYG{n}{System}\PYG{o}{.}\PYG{n+na}{out}\PYG{o}{.}\PYG{n+na}{println}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}Elapsed time \PYGZdq{}} \PYG{o}{+} \PYG{n}{t1} \PYG{o}{+} \PYG{l+s}{\PYGZdq{} milliseconds\PYGZdq{}}\PYG{o}{)}\PYG{o}{;}
      \PYG{o}{\PYGZcb{}}
\end{Verbatim}

\index{systolic arrays}\index{Actors}\index{dataflow}\index{parallelism!implicit}\index{implicit!parallelism}

\subsection{Scala Actors Implementation}
\label{actors:scala-actors-implementation}\label{actors:index-3}\begin{description}
\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} ZIP File}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala/get/default.zip}{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala/get/default.zip}

\item[{\raisebox{-0.5\height}{\includegraphics{bitbucket.png}} via Mercurial}] \leavevmode
hg clone \href{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala}

\item[{\raisebox{-0.5\height}{\includegraphics{instructions.png}} Build and Run Instructions}] \leavevmode
\href{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala}{https://bitbucket.org/loyolachicagocs\_plsystems/lcs-systolicarray-scala}

\end{description}

Trait

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{trait} \PYG{n+nc}{SystolicArray}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]} \PYG{o}{\PYGZob{}}
  \PYG{k}{def} \PYG{n}{start}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit}
  \PYG{k}{def} \PYG{n}{put}\PYG{o}{(}\PYG{n}{v}\PYG{k}{:} \PYG{k+kt}{T}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit}
  \PYG{k}{def} \PYG{n}{take}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{T}
  \PYG{k}{def} \PYG{n}{stop}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

The entire SystolicArray implementation is here:

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{trait} \PYG{n+nc}{SystolicArray}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]} \PYG{o}{\PYGZob{}}
  \PYG{k}{def} \PYG{n}{start}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit}
  \PYG{k}{def} \PYG{n}{put}\PYG{o}{(}\PYG{n}{v}\PYG{k}{:} \PYG{k+kt}{T}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit}
  \PYG{k}{def} \PYG{n}{take}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{T}
  \PYG{k}{def} \PYG{n}{stop}\PYG{o}{(}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

\index{technique!logging}\index{logging!technique}\phantomsection\label{actors:logging}
Logging
\begin{quote}

// begin-object-logger
\end{quote}

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{private} \PYG{k}{object} \PYG{n+nc}{logger} \PYG{o}{\PYGZob{}}
    \PYG{k}{private} \PYG{k}{val} \PYG{n+nc}{DEBUG} \PYG{k}{=} \PYG{k+kc}{false}
    \PYG{c+c1}{// use call\PYGZhy{}by\PYGZhy{}name to ensure the argument is evaluated on demand only}
    \PYG{k}{def} \PYG{n}{debug}\PYG{o}{(}\PYG{n}{msg}\PYG{k}{:} \PYG{o}{=\PYGZgt{}} \PYG{n+nc}{String}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{k}{if} \PYG{o}{(}\PYG{n+nc}{DEBUG}\PYG{o}{)} \PYG{n}{println}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}debug: \PYGZdq{}} \PYG{o}{+} \PYG{n}{msg}\PYG{o}{)} \PYG{o}{\PYGZcb{}}
    \PYG{c+c1}{// add other log levels as needed}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Apply

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{def} \PYG{n}{apply}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{(}\PYG{n}{rows}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{cols}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Acc}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{SystolicArray}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]} \PYG{k}{=} \PYG{o}{\PYGZob{}}
    \PYG{n}{require} \PYG{o}{\PYGZob{}} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}} \PYG{n}{rows} \PYG{o}{\PYGZcb{}}
    \PYG{n}{require} \PYG{o}{\PYGZob{}} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}} \PYG{n}{cols} \PYG{o}{\PYGZcb{}}
    \PYG{k}{val} \PYG{n}{result} \PYG{k}{=} \PYG{k}{new} \PYG{n+nc}{SyncVar}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}
    \PYG{k}{lazy} \PYG{k}{val} \PYG{n}{a}\PYG{k}{:} \PYG{k+kt}{LazyArray}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]} \PYG{k}{=} \PYG{n+nc}{Stream}\PYG{o}{.}\PYG{n}{tabulate}\PYG{o}{(}\PYG{n}{rows}\PYG{o}{,} \PYG{n}{cols}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{o}{(}\PYG{n}{i}\PYG{o}{,} \PYG{n}{j}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{k}{new} \PYG{n+nc}{Cell}\PYG{o}{(}\PYG{n}{i}\PYG{o}{,} \PYG{n}{j}\PYG{o}{,} \PYG{n}{rows}\PYG{o}{,} \PYG{n}{cols}\PYG{o}{,} \PYG{n}{a}\PYG{o}{,} \PYG{n}{f}\PYG{o}{,} \PYG{n}{result}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}
    \PYG{k}{val} \PYG{n}{root} \PYG{k}{=} \PYG{n}{a}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}
    \PYG{k}{new} \PYG{n+nc}{SystolicArray}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]} \PYG{o}{\PYGZob{}}
      \PYG{k}{override} \PYG{k}{def} \PYG{n}{start}\PYG{o}{(}\PYG{o}{)} \PYG{k}{=} \PYG{n}{root}\PYG{o}{.}\PYG{n}{start}\PYG{o}{(}\PYG{o}{)}
      \PYG{k}{override} \PYG{k}{def} \PYG{n}{put}\PYG{o}{(}\PYG{n}{v}\PYG{k}{:} \PYG{k+kt}{T}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{root} \PYG{o}{!} \PYG{o}{(}\PYG{o}{(}\PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{,} \PYG{o}{\PYGZhy{}}\PYG{l+m+mi}{1}\PYG{o}{)} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n}{v}\PYG{o}{)} \PYG{o}{\PYGZcb{}}
      \PYG{k}{override} \PYG{k}{def} \PYG{n}{take}\PYG{o}{(}\PYG{o}{)} \PYG{k}{=} \PYG{n}{result}\PYG{o}{.}\PYG{n}{take}\PYG{o}{(}\PYG{o}{)}
      \PYG{k}{override} \PYG{k}{def} \PYG{n}{stop}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{root} \PYG{o}{!} \PYG{n+nc}{Stop} \PYG{o}{\PYGZcb{}}
    \PYG{o}{\PYGZcb{}}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

The internal Cell class, used to represent the cells of the Systolic Array (generally).

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{protected} \PYG{k}{class} \PYG{n+nc}{Cell}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{(}\PYG{n}{row}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{col}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{rows}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{cols}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{,} \PYG{n}{a}\PYG{k}{:} \PYG{o}{=\PYGZgt{}} \PYG{n+nc}{LazyArray}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{,}
      \PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Acc}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{,} \PYG{n}{result}\PYG{k}{:} \PYG{k+kt}{SyncVar}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{)} \PYG{k}{extends} \PYG{n+nc}{Actor} \PYG{o}{\PYGZob{}} \PYG{n}{self} \PYG{k}{=\PYGZgt{}}

    \PYG{n}{require} \PYG{o}{\PYGZob{}} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}=} \PYG{n}{row} \PYG{o}{\PYGZam{}\PYGZam{}} \PYG{n}{row} \PYG{o}{\PYGZlt{}} \PYG{n}{rows} \PYG{o}{\PYGZcb{}}
    \PYG{n}{require} \PYG{o}{\PYGZob{}} \PYG{l+m+mi}{0} \PYG{o}{\PYGZlt{}=} \PYG{n}{col} \PYG{o}{\PYGZam{}\PYGZam{}} \PYG{n}{col} \PYG{o}{\PYGZlt{}} \PYG{n}{cols} \PYG{o}{\PYGZcb{}}

    \PYG{n}{logger}\PYG{o}{.}\PYG{n}{debug}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}creating (\PYGZdq{}} \PYG{o}{+} \PYG{n}{row} \PYG{o}{+} \PYG{l+s}{\PYGZdq{}, \PYGZdq{}} \PYG{o}{+} \PYG{n}{col} \PYG{o}{+} \PYG{l+s}{\PYGZdq{})\PYGZdq{}}\PYG{o}{)}

    \PYG{k}{override} \PYG{k}{def} \PYG{n}{act}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{n}{logger}\PYG{o}{.}\PYG{n}{debug}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}starting (\PYGZdq{}} \PYG{o}{+} \PYG{n}{row} \PYG{o}{+} \PYG{l+s}{\PYGZdq{}, \PYGZdq{}} \PYG{o}{+} \PYG{n}{col} \PYG{o}{+} \PYG{l+s}{\PYGZdq{})\PYGZdq{}}\PYG{o}{)}
      \PYG{k}{var} \PYG{n}{start} \PYG{k}{=} \PYG{k+kc}{true}
      \PYG{n}{loop} \PYG{o}{\PYGZob{}}
        \PYG{n}{logger}\PYG{o}{.}\PYG{n}{debug}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}waiting  (\PYGZdq{}} \PYG{o}{+} \PYG{n}{row} \PYG{o}{+} \PYG{l+s}{\PYGZdq{}, \PYGZdq{}} \PYG{o}{+} \PYG{n}{col} \PYG{o}{+} \PYG{l+s}{\PYGZdq{})\PYGZdq{}}\PYG{o}{)}
        \PYG{n}{barrier}\PYG{o}{(}\PYG{k}{if} \PYG{o}{(}\PYG{n}{row} \PYG{o}{==} \PYG{l+m+mi}{0} \PYG{o}{\textbar{}\textbar{}} \PYG{n}{col} \PYG{o}{==} \PYG{l+m+mi}{0}\PYG{o}{)} \PYG{l+m+mi}{1} \PYG{k}{else} \PYG{l+m+mi}{3}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{ms} \PYG{k}{=\PYGZgt{}}
          \PYG{k}{if} \PYG{o}{(}\PYG{n}{start}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{startNeighbors}\PYG{o}{(}\PYG{o}{)} \PYG{o}{;} \PYG{n}{start} \PYG{k}{=} \PYG{k+kc}{false} \PYG{o}{\PYGZcb{}}
          \PYG{n}{propagate}\PYG{o}{(}\PYG{n}{ms}\PYG{o}{)}
        \PYG{o}{\PYGZcb{}}
        \PYG{c+c1}{// one\PYGZhy{}way message: anything below here is skipped!}
      \PYG{o}{\PYGZcb{}}
    \PYG{o}{\PYGZcb{}}

    \PYG{k}{protected} \PYG{k}{def} \PYG{n}{barrier}\PYG{o}{(}\PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{o}{(}\PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{T}\PYG{o}{]} \PYG{k}{=\PYGZgt{}} \PYG{n+nc}{Unit}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit} \PYG{o}{=}
      \PYG{n}{barrier1}\PYG{o}{(}\PYG{n}{n}\PYG{o}{)}\PYG{o}{(}\PYG{n}{f}\PYG{o}{)}\PYG{o}{(}\PYG{n+nc}{Map}\PYG{o}{.}\PYG{n}{empty}\PYG{o}{)}

    \PYG{k}{protected} \PYG{k}{def} \PYG{n}{barrier1}\PYG{o}{(}\PYG{n}{n}\PYG{k}{:} \PYG{k+kt}{Int}\PYG{o}{)}\PYG{o}{(}\PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{T}\PYG{o}{]} \PYG{k}{=\PYGZgt{}} \PYG{n+nc}{Unit}\PYG{o}{)}\PYG{o}{(}\PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Unit} \PYG{o}{=} \PYG{o}{\PYGZob{}}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZlt{}=} \PYG{l+m+mi}{0}\PYG{o}{)}
        \PYG{n}{f}\PYG{o}{(}\PYG{n}{ms}\PYG{o}{)}
      \PYG{k}{else}
        \PYG{n}{react} \PYG{o}{\PYGZob{}}
          \PYG{k}{case} \PYG{n+nc}{Stop} \PYG{k}{=\PYGZgt{}} \PYG{n}{stopNeighbors}\PYG{o}{(}\PYG{o}{)} \PYG{o}{;} \PYG{n}{exit}\PYG{o}{(}\PYG{o}{)}
          \PYG{k}{case} \PYG{o}{(}\PYG{n}{p}\PYG{k}{:} \PYG{k+kt}{Pos}\PYG{o}{,} \PYG{n}{v}\PYG{k}{:} \PYG{k+kt}{T}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n}{barrier1}\PYG{o}{(}\PYG{n}{n} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{n}{f}\PYG{o}{)}\PYG{o}{(}\PYG{n}{ms} \PYG{o}{+} \PYG{o}{(}\PYG{n}{p} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n}{v}\PYG{o}{)}\PYG{o}{)}
        \PYG{o}{\PYGZcb{}}
      \PYG{c+c1}{// one\PYGZhy{}way message: anything after react is skipped!}
    \PYG{o}{\PYGZcb{}}

    \PYG{k}{protected} \PYG{k}{def} \PYG{n}{applyToNeighbors}\PYG{o}{(}\PYG{n}{f}\PYG{k}{:} \PYG{k+kt}{Cell}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]} \PYG{k}{=\PYGZgt{}} \PYG{n+nc}{Unit}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{row} \PYG{o}{\PYGZlt{}} \PYG{n}{rows} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}                   \PYG{n}{f}\PYG{o}{(}\PYG{n}{a}\PYG{o}{(}\PYG{n}{row} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{n}{col}    \PYG{o}{)}\PYG{o}{)}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{col} \PYG{o}{\PYGZlt{}} \PYG{n}{cols} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}                   \PYG{n}{f}\PYG{o}{(}\PYG{n}{a}\PYG{o}{(}\PYG{n}{row}    \PYG{o}{)}\PYG{o}{(}\PYG{n}{col} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{row} \PYG{o}{\PYGZlt{}} \PYG{n}{rows} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1} \PYG{o}{\PYGZam{}\PYGZam{}} \PYG{n}{col} \PYG{o}{\PYGZlt{}} \PYG{n}{cols} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)} \PYG{n}{f}\PYG{o}{(}\PYG{n}{a}\PYG{o}{(}\PYG{n}{row} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{n}{col} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}

    \PYG{k}{protected} \PYG{k}{def} \PYG{n}{startNeighbors}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{applyToNeighbors} \PYG{o}{\PYGZob{}} \PYG{k}{\PYGZus{}}\PYG{o}{.}\PYG{n}{start}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZcb{}} \PYG{o}{\PYGZcb{}}

    \PYG{k}{protected} \PYG{k}{def} \PYG{n}{propagate}\PYG{o}{(}\PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{)} \PYG{o}{\PYGZob{}}
      \PYG{k}{val} \PYG{n}{r} \PYG{k}{=} \PYG{n}{f}\PYG{o}{(}\PYG{o}{(}\PYG{n}{row}\PYG{o}{,} \PYG{n}{col}\PYG{o}{)}\PYG{o}{,} \PYG{n}{ms}\PYG{o}{)}
      \PYG{k}{val} \PYG{n}{m} \PYG{k}{=} \PYG{o}{(}\PYG{n}{row}\PYG{o}{,} \PYG{n}{col}\PYG{o}{)} \PYG{o}{\PYGZhy{}\PYGZgt{}} \PYG{n}{r}
      \PYG{n}{logger}\PYG{o}{.}\PYG{n}{debug}\PYG{o}{(}\PYG{l+s}{\PYGZdq{}firing   \PYGZdq{}} \PYG{o}{+} \PYG{n}{m}\PYG{o}{)}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{row} \PYG{o}{\PYGZlt{}} \PYG{n}{rows} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}                     \PYG{n}{a}\PYG{o}{(}\PYG{n}{row} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{n}{col}    \PYG{o}{)} \PYG{o}{!} \PYG{n}{m}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{col} \PYG{o}{\PYGZlt{}} \PYG{n}{cols} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}                     \PYG{n}{a}\PYG{o}{(}\PYG{n}{row}    \PYG{o}{)}\PYG{o}{(}\PYG{n}{col} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)} \PYG{o}{!} \PYG{n}{m}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{row} \PYG{o}{\PYGZlt{}} \PYG{n}{rows} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1} \PYG{o}{\PYGZam{}\PYGZam{}} \PYG{n}{col} \PYG{o}{\PYGZlt{}} \PYG{n}{cols} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}   \PYG{n}{a}\PYG{o}{(}\PYG{n}{row} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{(}\PYG{n}{col} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{)} \PYG{o}{!} \PYG{n}{m}
      \PYG{k}{if} \PYG{o}{(}\PYG{n}{row} \PYG{o}{\PYGZgt{}=} \PYG{n}{rows} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1} \PYG{o}{\PYGZam{}\PYGZam{}} \PYG{n}{col} \PYG{o}{\PYGZgt{}=} \PYG{n}{cols} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)} \PYG{n}{result}\PYG{o}{.}\PYG{n}{put}\PYG{o}{(}\PYG{n}{r}\PYG{o}{)}
    \PYG{o}{\PYGZcb{}}

    \PYG{k}{protected} \PYG{k}{def} \PYG{n}{stopNeighbors}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}} \PYG{n}{applyToNeighbors} \PYG{o}{\PYGZob{}} \PYG{k}{\PYGZus{}} \PYG{o}{!} \PYG{n+nc}{Stop} \PYG{o}{\PYGZcb{}} \PYG{o}{\PYGZcb{}}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

This is used for autowiring the quadrant from where messages are being fired (from). It is an example
of how Scala can help us avoid making mistakes. In scientific computations, subscript problems are common.

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{implicit} \PYG{k}{class} \PYG{n+nc}{Helper}\PYG{o}{[}\PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{(}\PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{T}\PYG{o}{]}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{k}{def} \PYG{n}{north}    \PYG{o}{(}\PYG{k}{implicit} \PYG{n}{current}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Pos}\PYG{o}{,} \PYG{k+kt}{T}\PYG{o}{)}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{T} \PYG{o}{=} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{o}{(}\PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{.}\PYG{n}{\PYGZus{}2}    \PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}2}\PYG{o}{)}
    \PYG{k}{def} \PYG{n}{west}     \PYG{o}{(}\PYG{k}{implicit} \PYG{n}{current}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Pos}\PYG{o}{,} \PYG{k+kt}{T}\PYG{o}{)}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{T} \PYG{o}{=} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{o}{(}\PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{.}\PYG{n}{\PYGZus{}1}    \PYG{o}{,} \PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}2}\PYG{o}{)}
    \PYG{k}{def} \PYG{n}{northwest}\PYG{o}{(}\PYG{k}{implicit} \PYG{n}{current}\PYG{k}{:} \PYG{o}{(}\PYG{k+kt}{Pos}\PYG{o}{,} \PYG{k+kt}{T}\PYG{o}{)}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{T} \PYG{o}{=} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{o}{(}\PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{n}{current}\PYG{o}{.}\PYG{n}{\PYGZus{}2}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

This is used to autowire the left and top edges of the array. Although easy enough to check, it can be
difficult to remember which subscript is row or column. Scala again makes this very easy for us. As we'll
see, it also helps to make the user function self-documenting (literate).

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  \PYG{k}{implicit} \PYG{k}{class} \PYG{n+nc}{PosHelper}\PYG{o}{(}\PYG{n}{p}\PYG{k}{:} \PYG{k+kt}{Pos}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{k}{def} \PYG{n}{north} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}
    \PYG{k}{def} \PYG{n}{west} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}
    \PYG{k}{def} \PYG{n}{isOnEdge} \PYG{k}{=} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{==} \PYG{l+m+mi}{0} \PYG{o}{\textbar{}\textbar{}} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{==} \PYG{l+m+mi}{0}
  \PYG{o}{\PYGZcb{}}
\end{Verbatim}

Wrapping it up with object lcs...

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{object} \PYG{n+nc}{lcs} \PYG{o}{\PYGZob{}}
  \PYG{k}{import} \PYG{n+nn}{SystolicArray.\PYGZus{}}

  \PYG{k}{def} \PYG{n}{f}\PYG{o}{(}\PYG{n}{c0}\PYG{k}{:} \PYG{k+kt}{String}\PYG{o}{,} \PYG{n}{c1}\PYG{k}{:} \PYG{k+kt}{String}\PYG{o}{)}\PYG{o}{(}\PYG{n}{p}\PYG{k}{:} \PYG{k+kt}{Pos}\PYG{o}{,} \PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)} \PYG{k}{=} \PYG{o}{\PYGZob{}}
    \PYG{k}{implicit} \PYG{k}{val} \PYG{n}{currentPosAndDefaultValue} \PYG{k}{=} \PYG{o}{(}\PYG{n}{p}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{)}
    \PYG{k}{if} \PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{isOnEdge}\PYG{o}{)}
      \PYG{l+m+mi}{0}
    \PYG{k}{else} \PYG{k}{if} \PYG{o}{(}\PYG{n}{c0}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{north}\PYG{o}{)} \PYG{o}{==} \PYG{n}{c1}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{west}\PYG{o}{)}\PYG{o}{)}
      \PYG{n}{ms}\PYG{o}{.}\PYG{n}{northwest} \PYG{o}{+} \PYG{l+m+mi}{1}
    \PYG{k}{else}
      \PYG{n}{math}\PYG{o}{.}\PYG{n}{max}\PYG{o}{(}\PYG{n}{ms}\PYG{o}{.}\PYG{n}{west}\PYG{o}{,} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{north}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}

  \PYG{k}{def} \PYG{n}{apply}\PYG{o}{(}\PYG{n}{c0}\PYG{k}{:} \PYG{k+kt}{String}\PYG{o}{,} \PYG{n}{c1}\PYG{k}{:} \PYG{k+kt}{String}\PYG{o}{)}\PYG{k}{:} \PYG{k+kt}{Int} \PYG{o}{=} \PYG{o}{\PYGZob{}}
    \PYG{k}{val} \PYG{n}{root} \PYG{k}{=} \PYG{n+nc}{SystolicArray}\PYG{o}{(}\PYG{n}{c0}\PYG{o}{.}\PYG{n}{length} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{c1}\PYG{o}{.}\PYG{n}{length} \PYG{o}{+} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{f}\PYG{o}{(}\PYG{n}{c0}\PYG{o}{,} \PYG{n}{c1}\PYG{o}{)}\PYG{o}{)}
    \PYG{n}{root}\PYG{o}{.}\PYG{n}{start}\PYG{o}{(}\PYG{o}{)}
    \PYG{n}{root}\PYG{o}{.}\PYG{n}{put}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}
    \PYG{n}{root}\PYG{o}{.}\PYG{n}{take}
  \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

Setting up the text fixtures...

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{object} \PYG{n+nc}{Fixtures} \PYG{o}{\PYGZob{}}
  \PYG{k}{import} \PYG{n+nn}{SystolicArray.\PYGZus{}}

  \PYG{k}{val} \PYG{n}{c0} \PYG{k}{=} \PYG{l+s}{\PYGZdq{}Now is the time for all great women to come to the aid of their country\PYGZdq{}}

  \PYG{k}{val} \PYG{n}{c1} \PYG{k}{=} \PYG{l+s}{\PYGZdq{}Now all great women will come to the aid of their country\PYGZdq{}}

  \PYG{k}{val} \PYG{n}{f1} \PYG{k}{=} \PYG{o}{(}\PYG{n}{p}\PYG{k}{:} \PYG{k+kt}{Pos}\PYG{o}{,} \PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{values}\PYG{o}{.}\PYG{n}{sum}

  \PYG{k}{val} \PYG{n}{f2} \PYG{k}{=} \PYG{o}{(}\PYG{n}{p}\PYG{k}{:} \PYG{k+kt}{Pos}\PYG{o}{,} \PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
    \PYG{k}{implicit} \PYG{k}{val} \PYG{n}{currentPosAndDefaultValue} \PYG{k}{=} \PYG{o}{(}\PYG{n}{p}\PYG{o}{,} \PYG{l+m+mi}{0}\PYG{o}{)}
    \PYG{n}{ms}\PYG{o}{.}\PYG{n}{north} \PYG{o}{+} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{northwest} \PYG{o}{+} \PYG{n}{ms}\PYG{o}{.}\PYG{n}{west}
  \PYG{o}{\PYGZcb{}}

  \PYG{k}{val} \PYG{n}{f3} \PYG{k}{=} \PYG{n}{lcs}\PYG{o}{.}\PYG{n}{f}\PYG{o}{(}\PYG{n}{c0}\PYG{o}{,} \PYG{n}{c1}\PYG{o}{)} \PYG{k}{\PYGZus{}}

  \PYG{c+c1}{// \PYGZdq{}bare\PYGZhy{}metal\PYGZdq{} version of lcs, does not run significantly faster}
  \PYG{k}{val} \PYG{n}{f4} \PYG{k}{=} \PYG{o}{(}\PYG{n}{p}\PYG{k}{:} \PYG{k+kt}{Pos}\PYG{o}{,} \PYG{n}{ms}\PYG{k}{:} \PYG{k+kt}{Map}\PYG{o}{[}\PYG{k+kt}{Pos}, \PYG{k+kt}{Int}\PYG{o}{]}\PYG{o}{)} \PYG{k}{=\PYGZgt{}} \PYG{o}{\PYGZob{}}
    \PYG{k}{if} \PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{==} \PYG{l+m+mi}{0} \PYG{o}{\textbar{}\textbar{}} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{==} \PYG{l+m+mi}{0}\PYG{o}{)}
      \PYG{l+m+mi}{0}
    \PYG{k}{else} \PYG{k}{if} \PYG{o}{(}\PYG{n}{c0}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)} \PYG{o}{==} \PYG{n}{c1}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}
      \PYG{n}{ms}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)} \PYG{o}{+} \PYG{l+m+mi}{1}
    \PYG{k}{else}
      \PYG{n}{math}\PYG{o}{.}\PYG{n}{max}\PYG{o}{(}
        \PYG{n}{ms}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{,} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{,}
        \PYG{n}{ms}\PYG{o}{.}\PYG{n}{get}\PYG{o}{(}\PYG{o}{(}\PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}1}\PYG{o}{,} \PYG{n}{p}\PYG{o}{.}\PYG{n}{\PYGZus{}2} \PYG{o}{\PYGZhy{}} \PYG{l+m+mi}{1}\PYG{o}{)}\PYG{o}{)}\PYG{o}{.}\PYG{n}{getOrElse}\PYG{o}{(}\PYG{l+m+mi}{0}\PYG{o}{)}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}

Testing...

\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
\PYG{k}{class} \PYG{n+nc}{Tests} \PYG{o}{\PYGZob{}}

  \PYG{n+nd}{@Test} \PYG{k}{def} \PYG{n}{testSum}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{k}{val} \PYG{n}{root} \PYG{k}{=} \PYG{n+nc}{SystolicArray}\PYG{o}{(}\PYG{l+m+mi}{3}\PYG{o}{,} \PYG{l+m+mi}{3}\PYG{o}{,} \PYG{n}{f1}\PYG{o}{)}
    \PYG{n}{root}\PYG{o}{.}\PYG{n}{start}\PYG{o}{(}\PYG{o}{)}
    \PYG{n}{root}\PYG{o}{.}\PYG{n}{put}\PYG{o}{(}\PYG{l+m+mi}{1}\PYG{o}{)}
    \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{13}\PYG{o}{,} \PYG{n}{root}\PYG{o}{.}\PYG{n}{take}\PYG{o}{(}\PYG{o}{)}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}

  \PYG{n+nd}{@Test} \PYG{k}{def} \PYG{n}{testSample}\PYG{o}{(}\PYG{o}{)} \PYG{o}{\PYGZob{}}
    \PYG{n}{assertEquals}\PYG{o}{(}\PYG{l+m+mi}{53}\PYG{o}{,} \PYG{n}{lcs}\PYG{o}{(}\PYG{n}{c0}\PYG{o}{,} \PYG{n}{c1}\PYG{o}{)}\PYG{o}{)}
  \PYG{o}{\PYGZcb{}}
\PYG{o}{\PYGZcb{}}
\end{Verbatim}


\section{Programming Language Topics}
\label{pl:programming-language-topics}\label{pl::doc}

\subsection{Abstraction}
\label{abstraction:abstraction}\label{abstraction::doc}
Topics
\begin{itemize}
\item {} 
higher-order methods

\item {} 
traits

\item {} 
genericity

\end{itemize}


\subsection{Representation}
\label{representation:representation}\label{representation::doc}
Topics
\begin{itemize}
\item {} 
algebraic data types

\item {} 
lexing and parsing

\item {} 
interpreters

\item {} 
domain-specific languages

\end{itemize}


\chapter{Indices and tables}
\label{index:indices-and-tables}\begin{itemize}
\item {} 
\emph{genindex}

\item {} 
\emph{search}

\end{itemize}

\begin{thebibliography}{MiscExplorationsScala}
\bibitem[RedmonkPL]{RedmonkPL}{\phantomsection\label{intro:redmonkpl} 
Redmonk Programming Language Rankings, \href{http://redmonk.com/sogrady/2014/01/22/language-rankings-1-14/}{http://redmonk.com/sogrady/2014/01/22/language-rankings-1-14/}
}
\bibitem[ScalaWikipedia]{ScalaWikipedia}{\phantomsection\label{intro:scalawikipedia} 
Scala Programming Language, Wikipedia, \href{http://en.wikipedia.org/wiki/Scala\_(programming\_language}{http://en.wikipedia.org/wiki/Scala\_(programming\_language})
}
\bibitem[LaScala]{LaScala}{\phantomsection\label{intro:lascala} 
La Scala, Wikimedia Commons, \href{http://en.wikipedia.org/wiki/File:Milano-scalanotte\_e.jpg}{http://en.wikipedia.org/wiki/File:Milano-scalanotte\_e.jpg}
}
\bibitem[LaScalaConcert]{LaScalaConcert}{\phantomsection\label{intro:lascalaconcert} 
Keith Jarrett, \href{http://en.wikipedia.org/wiki/La\_Scala\_(album}{http://en.wikipedia.org/wiki/La\_Scala\_(album}){}`
}
\bibitem[TailCalls]{TailCalls}{\phantomsection\label{cs1:tailcalls} 
Tail Call, \href{http://en.wikipedia.org/wiki/Tail\_call}{http://en.wikipedia.org/wiki/Tail\_call}
}
\bibitem[GCD]{GCD}{\phantomsection\label{cs1:id5} 
Greatest Common Divisor, \href{http://introcs.cs.luc.edu/html/gcdexamples.html}{http://introcs.cs.luc.edu/html/gcdexamples.html}
}
\bibitem[MiscExplorationsScala]{MiscExplorationsScala}{\phantomsection\label{cs1:miscexplorationsscala} 
Miscellaneous Scala Explorations, \href{https://bitbucket.org/lucproglangcourse/misc-explorations-scala}{https://bitbucket.org/lucproglangcourse/misc-explorations-scala}
}
\bibitem[ScalaAPI]{ScalaAPI}{\phantomsection\label{cs1:scalaapi} 
Scala API Documentation, \href{http://www.scala-lang.org/api/current/\#package}{http://www.scala-lang.org/api/current/\#package}
}
\bibitem[Wavefront]{Wavefront}{\phantomsection\label{actors:wavefront} \begin{enumerate}
\setcounter{enumi}{7}
\item {} \begin{enumerate}
\setcounter{enumi}{19}
\item {} 
Kung, C. E. Leiserson: Algorithms for VLSI processor arrays; in: C. Mead, L. Conway (eds.): Introduction to VLSI Systems; Addison-Wesley, 1979

\end{enumerate}

\end{enumerate}
}
\bibitem[HPJPC]{HPJPC}{\phantomsection\label{actors:hpjpc} 
Thomas W. Christopher and George K. Thiruvathukal, \emph{High Performance Java Platform Computing}, Prentice Hall PTR and Sun Microsystems Press, 2000.
}
\end{thebibliography}



\renewcommand{\indexname}{Index}
\printindex
\end{document}
