author | Christian Urban <christian dot urban at kcl dot ac dot uk> |
Tue, 06 Aug 2019 00:12:34 +0100 | |
changeset 270 | b9eaa5cdec4a |
parent 269 | 86a85865e772 |
child 271 | 48e12e7aee6e |
permissions | -rw-r--r-- |
197 | 1 |
% !TEX program = xelatex |
123 | 2 |
\documentclass{article} |
3 |
\usepackage{../style} |
|
4 |
\usepackage{../langs} |
|
5 |
\usepackage{marvosym} |
|
184 | 6 |
\usepackage{boxedminipage} |
123 | 7 |
|
8 |
%cheat sheet |
|
9 |
%http://worldline.github.io/scala-cheatsheet/ |
|
10 |
||
181 | 11 |
% case class, apply, unapply |
170 | 12 |
% see https://medium.com/@thejasbabu/scala-pattern-matching-9c9e73ba9a8a |
13 |
||
191 | 14 |
% the art of programming |
15 |
% https://www.youtube.com/watch?v=QdVFvsCWXrA |
|
16 |
||
17 |
% functional programming in Scala |
|
18 |
%https://www.amazon.com/gp/product/1449311032/ref=as_li_ss_tl?ie=UTF8&tag=aleottshompag-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1449311032 |
|
19 |
||
197 | 20 |
% functional programming in C |
191 | 21 |
%https://www.amazon.com/gp/product/0201419505/ref=as_li_ss_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=0201419505&linkCode=as2&tag=aleottshompag-20 |
22 |
||
23 |
%speeding through haskell |
|
24 |
%https://openlibra.com/en/book/download/speeding-through-haskell |
|
25 |
||
26 |
% fp books --- ocaml |
|
27 |
% http://courses.cms.caltech.edu/cs134/cs134b/book.pdf |
|
28 |
% http://alexott.net/en/fp/books/ |
|
29 |
||
257 | 30 |
%John Hughes’ simple words: |
31 |
%A combinator is a function which builds program fragments |
|
32 |
%from program fragments. |
|
33 |
||
34 |
||
264 | 35 |
%explain graph coloring program (examples from) |
36 |
%https://www.metalevel.at/prolog/optimization |
|
37 |
||
38 |
||
39 |
% nice example for map and reduce using Harry potter characters |
|
40 |
% https://www.matthewgerstman.com/map-filter-reduce/ |
|
41 |
||
42 |
||
123 | 43 |
\begin{document} |
180 | 44 |
\fnote{\copyright{} Christian Urban, King's College London, 2017, 2018} |
123 | 45 |
|
125 | 46 |
\section*{A Crash-Course in Scala} |
123 | 47 |
|
182 | 48 |
\mbox{}\hfill\textit{``Scala --- \underline{S}lowly \underline{c}ompiled |
49 |
\underline{a}cademic \underline{la}nguage''}\smallskip\\ |
|
192 | 50 |
\mbox{}\hfill\textit{ --- a joke(?) found on Twitter}\bigskip |
195 | 51 |
|
52 |
||
53 |
\subsection*{Introduction} |
|
54 |
||
178 | 55 |
\noindent |
170 | 56 |
Scala is a programming language that combines functional and |
57 |
object-oriented programming-styles. It has received quite a bit of |
|
181 | 58 |
attention in the last five or so years. One reason for this attention is |
59 |
that, like the Java programming language, Scala compiles to the Java |
|
60 |
Virtual Machine (JVM) and therefore Scala programs can run under MacOSX, |
|
195 | 61 |
Linux and Windows. Because of this it has also access to |
181 | 62 |
the myriads of Java libraries. Unlike Java, however, Scala often allows |
186 | 63 |
programmers to write very concise and elegant code. Some therefore say |
182 | 64 |
``Scala is the better Java''.\footnote{from |
188 | 65 |
\url{https://www.slideshare.net/maximnovak/joy-of-scala}} |
66 |
||
191 | 67 |
A number of companies---the Guardian, Twitter, Coursera, FourSquare, |
68 |
Netflix, LinkedIn, ITV to name a few---either use Scala exclusively in |
|
188 | 69 |
production code, or at least to some substantial degree. Scala seems |
70 |
also useful in job-interviews (especially in data science) according to |
|
71 |
this anecdotal report |
|
170 | 72 |
|
181 | 73 |
\begin{quote} |
74 |
\url{http://techcrunch.com/2016/06/14/scala-is-the-new-golden-child} |
|
170 | 75 |
\end{quote} |
76 |
||
77 |
\noindent |
|
78 |
The official Scala compiler can be downloaded from |
|
79 |
||
80 |
\begin{quote} |
|
195 | 81 |
\url{http://www.scala-lang.org}\medskip |
82 |
\end{quote} |
|
170 | 83 |
|
84 |
\noindent |
|
265 | 85 |
If you are interested, there are also experimental backends of Scala |
195 | 86 |
for producing code under Android (\url{http://scala-android.org}); for |
87 |
generating JavaScript code (\url{https://www.scala-js.org}); and there |
|
88 |
is work under way to have a native Scala compiler generating X86-code |
|
89 |
(\url{http://www.scala-native.org}). Though be warned these backends |
|
90 |
are still rather beta or even alpha. |
|
91 |
||
92 |
\subsection*{VS Code and Scala} |
|
93 |
||
184 | 94 |
I found a convenient IDE for writing Scala programs is Microsoft's |
181 | 95 |
\textit{Visual Studio Code} (VS Code) which runs under MacOSX, Linux and |
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
96 |
obviously Windows.\footnote{\ldots{}unlike \emph{Microsoft Visual Studio}---note |
191 | 97 |
the minuscule difference in the name---which is a heavy-duty, |
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
98 |
Windows-only IDE\ldots{}jeez, with all their money could they not have come |
191 | 99 |
up with a completely different name for a complete different project? |
100 |
For the pedantic, Microsoft Visual Studio is an IDE, whereas Visual |
|
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
101 |
Studio Code is considered to be a \emph{source code editor}. Anybody knows what the |
191 | 102 |
difference is?} It can be downloaded for free from |
181 | 103 |
|
104 |
\begin{quote} |
|
105 |
\url{https://code.visualstudio.com} |
|
106 |
\end{quote} |
|
107 |
||
108 |
\noindent |
|
109 |
and should already come pre-installed in the Department (together with |
|
195 | 110 |
the Scala compiler). Being a project that just started in 2015, VS Code is |
189 | 111 |
relatively new and thus far from perfect. However it includes a |
182 | 112 |
\textit{Marketplace} from which a multitude of extensions can be |
184 | 113 |
downloaded that make editing and running Scala code a little easier (see |
114 |
Figure~\ref{vscode} for my setup). |
|
181 | 115 |
|
116 |
\begin{figure}[t] |
|
184 | 117 |
\begin{boxedminipage}{\textwidth} |
181 | 118 |
\begin{center} |
119 |
\includegraphics[scale=0.15]{../pics/vscode.png}\\[-10mm]\mbox{} |
|
120 |
\end{center} |
|
195 | 121 |
\caption{My installation of VS Code includes the following |
122 |
packages from Marketplace: \textbf{Scala Syntax (official)} 0.2.0, |
|
123 |
\textbf{Code Runner} 0.9.5, \textbf{Code Spell Checker} 1.6.10, |
|
124 |
\textbf{Rewrap} 1.9.1 and \textbf{Subtle Match |
|
125 |
Brackets} 3.0.0. I have also bound the keys \keys{Ctrl} \keys{Ret} to the |
|
126 |
action ``Run-Selected-Text-In-Active-Terminal'' in order to quickly |
|
127 |
evaluate small code snippets in the Scala REPL.\label{vscode}} |
|
184 | 128 |
\end{boxedminipage} |
181 | 129 |
\end{figure} |
130 |
||
184 | 131 |
What I like most about VS Code is that it provides easy access to the |
186 | 132 |
Scala REPL. But if you prefer another editor for coding, it is also |
133 |
painless to work with Scala completely on the command line (as you might |
|
134 |
have done with \texttt{g++} in the earlier part of PEP). For the |
|
195 | 135 |
lazybones among us, there are even online editors and environments for |
197 | 136 |
developing and running Scala programs: \textit{ScalaFiddle} |
137 |
and \textit{Scastie} are two of them. They require zero setup |
|
138 |
(assuming you have a browser handy). You can access them at |
|
181 | 139 |
|
140 |
\begin{quote} |
|
195 | 141 |
\url{https://scalafiddle.io}\\ |
142 |
\url{https://scastie.scala-lang.org}\medskip |
|
181 | 143 |
\end{quote} |
144 |
||
195 | 145 |
\noindent |
197 | 146 |
But you should be careful if you use them for your coursework: they |
147 |
are meant to play around, not really for serious work. |
|
148 |
||
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
149 |
As one might expect, Scala can be used with the heavy-duty IDEs Eclipse and IntelliJ. |
182 | 150 |
A ready-made Scala bundle for Eclipse is available from |
170 | 151 |
|
152 |
\begin{quote} |
|
153 |
\url{http://scala-ide.org/download/sdk.html} |
|
154 |
\end{quote} |
|
155 |
||
156 |
\noindent |
|
191 | 157 |
Also IntelliJ includes plugins for Scala. \underline{\textbf{BUT}}, |
158 |
I do \textbf{not} recommend the usage of either Eclipse or IntelliJ for PEP: these IDEs |
|
182 | 159 |
seem to make your life harder, rather than easier, for the small |
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
160 |
programs that we will write in this module. They are really meant to be used |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
161 |
when you have a million-lines codebase than with our small |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
162 |
``toy-programs''\ldots{}for example why on earth am I required to create a |
182 | 163 |
completely new project with several subdirectories when I just want to |
186 | 164 |
try out 20-lines of Scala code? Your mileage may vary though. ;o) |
182 | 165 |
|
166 |
\subsection*{Why Functional Programming?} |
|
167 |
||
186 | 168 |
Before we go on, let me explain a bit more why we want to inflict upon |
169 |
you another programming language. You hopefully have mastered Java and |
|
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
170 |
C++\ldots{}the world should be your oyster, no? Well, this is not as |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
171 |
simple as one might wish. We do require Scala in PEP, but actually we |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
172 |
do not religiously care whether you learn Scala---after all it is just |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
173 |
a programming language (albeit a nifty one IMHO). What we do care |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
174 |
about is that you learn about \textit{functional programming}. Scala |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
175 |
is just the vehicle for that. Still, you need to learn Scala well |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
176 |
enough to get good marks in PEP, but functional programming could |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
177 |
equally be taught with Haskell, F\#, SML, Ocaml, Kotlin, Clojure, |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
178 |
Scheme, Elm and many other functional programming languages. |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
179 |
%Your |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
180 |
%friendly lecturer just happens to like Scala |
186 | 181 |
%and the Department agreed that it is a good idea to inflict Scala upon |
182 |
%you. |
|
182 | 183 |
|
184 |
Very likely writing programs in a functional programming language is |
|
183 | 185 |
quite different from what you are used to in your study so far. It |
186 |
might even be totally alien to you. The reason is that functional |
|
187 |
programming seems to go against the core principles of |
|
188 |
\textit{imperative programming} (which is what you do in Java and C++ |
|
189 |
for example). The main idea of imperative programming is that you have |
|
191 | 190 |
some form of \emph{state} in your program and you continuously change this |
191 |
state by issuing some commands---for example for updating a field in an |
|
197 | 192 |
array or for adding one to a variable and so on. The classic |
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
193 |
example for this style of programming is \texttt{for}-loops in C/C++. Consider |
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
194 |
the snippet: |
182 | 195 |
|
196 |
\begin{lstlisting}[language=C,numbers=none] |
|
184 | 197 |
for (int i = 10; i < 20; i++) { |
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
198 |
//...do something with i... |
184 | 199 |
} |
182 | 200 |
\end{lstlisting} |
201 |
||
184 | 202 |
\noindent Here the integer variable \texttt{i} embodies the state, which |
203 |
is first set to \texttt{10} and then increased by one in each |
|
204 |
loop-iteration until it reaches \texttt{20} at which point the loop |
|
205 |
exits. When this code is compiled and actually runs, there will be some |
|
186 | 206 |
dedicated space reserved for \texttt{i} in memory. This space of |
188 | 207 |
typically 32 bits contains \texttt{i}'s current value\ldots\texttt{10} |
269
86a85865e772
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
265
diff
changeset
|
208 |
at the beginning, and then the content will be overwritten with |
191 | 209 |
new content in every iteration. The main point here is that this kind of |
210 |
updating, or manipulating, memory is 25.806\ldots or \textbf{THE ROOT OF |
|
211 |
ALL EVIL}!! |
|
186 | 212 |
|
213 |
\begin{center} |
|
214 |
\includegraphics[scale=0.25]{../pics/root-of-all-evil.png} |
|
215 |
\end{center} |
|
216 |
||
182 | 217 |
|
218 |
\noindent |
|
219 |
\ldots{}Well, it is perfectly benign if you have a sequential program |
|
220 |
that gets run instruction by instruction...nicely one after another. |
|
221 |
This kind of running code uses a single core of your CPU and goes as |
|
184 | 222 |
fast as your CPU frequency, also called clock-speed, allows. The problem |
223 |
is that this clock-speed has not much increased over the past decade and |
|
224 |
no dramatic increases are predicted for any time soon. So you are a bit |
|
225 |
stuck, unlike previous generations of developers who could rely upon the |
|
226 |
fact that every 2 years or so their code would run twice as fast (in |
|
227 |
ideal circumstances) because the clock-speed of their CPUs got twice as |
|
228 |
fast. This unfortunately does not happen any more nowadays. To get you |
|
229 |
out of this dreadful situation, CPU producers pile more and more |
|
230 |
cores into CPUs in order to make them more powerful and potentially make |
|
231 |
software faster. The task for you as developer is to take somehow |
|
232 |
advantage of these cores by running as much of your code as possible in |
|
186 | 233 |
parallel on as many cores you have available (typically 4 in modern |
184 | 234 |
laptops and sometimes much more on high-end machines). In this |
235 |
situation, \textit{mutable} variables like \texttt{i} above are evil, or |
|
236 |
at least a major nuisance: Because if you want to distribute some of the |
|
183 | 237 |
loop-iterations over the cores that are currently idle in your system, |
186 | 238 |
you need to be extremely careful about who can read and overwrite |
239 |
the variable \texttt{i}.\footnote{If you are of the mistaken belief that nothing |
|
183 | 240 |
nasty can happen to \texttt{i} inside the \texttt{for}-loop, then you |
241 |
need to go back over the C++ material.} Especially the writing operation |
|
242 |
is critical because you do not want that conflicting writes mess about |
|
184 | 243 |
with \texttt{i}. Take my word: an untold amount of misery has arisen |
244 |
from this problem. The catch is that if you try to solve this problem in |
|
245 |
C++ or Java, and be as defensive as possible about reads and writes to |
|
246 |
\texttt{i}, then you need to synchronise access to it. The result is that |
|
183 | 247 |
your program more often than not waits more than it runs, thereby |
248 |
defeating the point of trying to run the program in parallel in the |
|
249 |
first place. If you are less defensive, then usually all hell breaks |
|
250 |
loose by seemingly obtaining random results. And forget the idea of |
|
251 |
being able to debug such code. |
|
182 | 252 |
|
184 | 253 |
The central idea of functional programming is to eliminate any state |
195 | 254 |
from programs---or at least from the ``interesting bits'' of the |
255 |
programs. Because then it is easy to parallelise the resulting |
|
256 |
programs: if you do not have any state, then once created, all memory |
|
257 |
content stays unchanged and reads to such memory are absolutely safe |
|
258 |
without the need of any synchronisation. An example is given in |
|
259 |
Figure~\ref{mand} where in the absence of the annoying state, Scala |
|
260 |
makes it very easy to calculate the Mandelbrot set on as many cores of |
|
261 |
your CPU as possible. Why is it so easy in this example? Because each |
|
262 |
pixel in the Mandelbrot set can be calculated independently and the |
|
263 |
calculation does not need to update any variable. It is so easy in |
|
264 |
fact that going from the sequential version of the Mandelbrot program |
|
265 |
to the parallel version can be achieved by adding just eight |
|
266 |
characters---in two places you have to add \texttt{.par}. Try the same |
|
267 |
in C++ or Java! |
|
182 | 268 |
|
269 |
\begin{figure}[p] |
|
184 | 270 |
\begin{boxedminipage}{\textwidth} |
187 | 271 |
|
191 | 272 |
A Scala program for generating pretty pictures of the Mandelbrot set.\smallskip\\ |
273 |
(See \url{https://en.wikipedia.org/wiki/Mandelbrot_set} or\\ |
|
274 |
\phantom{(See }\url{https://www.youtube.com/watch?v=aSg2Db3jF_4}): |
|
184 | 275 |
\begin{center} |
276 |
\begin{tabular}{c} |
|
191 | 277 |
\includegraphics[scale=0.11]{../pics/mand1.png}\\[-8mm]\mbox{} |
184 | 278 |
\end{tabular} |
187 | 279 |
\end{center} |
184 | 280 |
|
187 | 281 |
\begin{center} |
282 |
\begin{tabular}{@{}p{0.45\textwidth}|p{0.45\textwidth}@{}} |
|
191 | 283 |
\bf sequential version: & \bf parallel version on 4 cores:\smallskip\\ |
182 | 284 |
|
191 | 285 |
{\hfill\includegraphics[scale=0.11]{../pics/mand4.png}\hfill} & |
286 |
{\hfill\includegraphics[scale=0.11]{../pics/mand3.png}\hfill} \\ |
|
187 | 287 |
|
288 |
{\footnotesize\begin{lstlisting}[xleftmargin=-1mm] |
|
186 | 289 |
for (y <- (0 until H)) { |
290 |
for (x <- (0 until W)) { |
|
291 |
||
292 |
val c = start + |
|
293 |
(x * d_x + y * d_y * i) |
|
294 |
val iters = iterations(c, max) |
|
191 | 295 |
val colour = |
186 | 296 |
if (iters == max) black |
297 |
else colours(iters % 16) |
|
298 |
||
191 | 299 |
pixel(x, y, colour) |
186 | 300 |
} |
301 |
viewer.updateUI() |
|
302 |
} |
|
187 | 303 |
\end{lstlisting}} |
304 |
& |
|
305 |
{\footnotesize\begin{lstlisting}[xleftmargin=0mm] |
|
188 | 306 |
for (y <- (0 until H)/*@\keys{\texttt{.par}}@*/) { |
307 |
for (x <- (0 until W)/*@\keys{\texttt{.par}}@*/) { |
|
187 | 308 |
|
309 |
val c = start + |
|
310 |
(x * d_x + y * d_y * i) |
|
311 |
val iters = iterations(c, max) |
|
191 | 312 |
val colour = |
187 | 313 |
if (iters == max) black |
314 |
else colours(iters % 16) |
|
315 |
||
191 | 316 |
pixel(x, y, colour) |
187 | 317 |
} |
318 |
viewer.updateUI() |
|
319 |
} |
|
191 | 320 |
\end{lstlisting}}\\[-2mm] |
187 | 321 |
|
322 |
\centering\includegraphics[scale=0.5]{../pics/cpu2.png} & |
|
188 | 323 |
\centering\includegraphics[scale=0.5]{../pics/cpu1.png} |
184 | 324 |
\end{tabular} |
325 |
\end{center} |
|
270
b9eaa5cdec4a
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
269
diff
changeset
|
326 |
\caption{The code of the ``main'' loops in my version of the mandelbrot program. |
191 | 327 |
The parallel version differs only in \texttt{.par} being added to the |
195 | 328 |
``ranges'' of the x and y coordinates. As can be seen from the CPU loads, in |
329 |
the sequential version there is a lower peak for an extended period, |
|
191 | 330 |
while in the parallel version there is a short sharp burst for |
331 |
essentially the same workload\ldots{}meaning you get more work done |
|
195 | 332 |
in a shorter amount of time. This easy \emph{parallelisation} |
333 |
only works reliably with an immutable program. |
|
188 | 334 |
\label{mand}} |
184 | 335 |
\end{boxedminipage} |
182 | 336 |
\end{figure} |
337 |
||
188 | 338 |
But remember this easy parallelisation of code requires that we |
339 |
have no state in our programs\ldots{}that is no counters like |
|
186 | 340 |
\texttt{i} in \texttt{for}-loops. You might then ask, how do I write |
341 |
loops without such counters? Well, teaching you that this is possible is |
|
342 |
one of the main points of the Scala-part in PEP. I can assure you it is |
|
343 |
possible, but you have to get your head around it. Once you have |
|
344 |
mastered this, it will be fun to have no state in your programs (a side |
|
345 |
product is that it much easier to debug state-less code and also more |
|
188 | 346 |
often than not easier to understand). So have fun with |
186 | 347 |
Scala!\footnote{If you are still not convinced about the function |
348 |
programming ``thing'', there are a few more arguments: a lot of research |
|
349 |
in programming languages happens to take place in functional programming |
|
350 |
languages. This has resulted in ultra-useful features such as |
|
191 | 351 |
pattern-matching, strong type-systems, laziness, implicits, algebraic |
188 | 352 |
datatypes to name a few. Imperative languages seem to often lag behind |
186 | 353 |
in adopting them: I know, for example, that Java will at some point in |
191 | 354 |
the future support pattern-matching, which has been used for example |
355 |
in SML for at |
|
186 | 356 |
least 40(!) years. See |
357 |
\url{http://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html}. |
|
358 |
Also Rust, a C-like programming language that has been developed since |
|
359 |
2010 and is gaining quite some interest, borrows many ideas from |
|
360 |
functional programming from yesteryear.} |
|
170 | 361 |
|
188 | 362 |
|
123 | 363 |
\subsection*{The Very Basics} |
364 |
||
365 |
One advantage of Scala over Java is that it includes an interpreter (a |
|
366 |
REPL, or |
|
367 |
\underline{R}ead-\underline{E}val-\underline{P}rint-\underline{L}oop) |
|
181 | 368 |
with which you can run and test small code snippets without the need |
123 | 369 |
of a compiler. This helps a lot with interactively developing |
188 | 370 |
programs. It is my preferred way of writing small Scala |
123 | 371 |
programs. Once you installed Scala, you can start the interpreter by |
372 |
typing on the command line: |
|
373 |
||
374 |
\begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small] |
|
375 |
$ scala |
|
195 | 376 |
Welcome to Scala 2.12.7 (Java HotSpot(TM) 64-Bit Server VM, Java 9). |
123 | 377 |
Type in expressions for evaluation. Or try :help. |
378 |
||
379 |
scala> |
|
380 |
\end{lstlisting}%$ |
|
381 |
||
382 |
\noindent The precise response may vary depending |
|
383 |
on the version and platform where you installed Scala. At the Scala |
|
384 |
prompt you can type things like \code{2 + 3}\;\keys{Ret} and |
|
385 |
the output will be |
|
386 |
||
387 |
\begin{lstlisting}[numbers=none] |
|
388 |
scala> 2 + 3 |
|
389 |
res0: Int = 5 |
|
390 |
\end{lstlisting} |
|
391 |
||
188 | 392 |
\noindent The answer means that he result of the addition is of type |
124 | 393 |
\code{Int} and the actual result is 5; \code{res0} is a name that |
125 | 394 |
Scala gives automatically to the result. You can reuse this name later |
188 | 395 |
on, for example |
181 | 396 |
|
397 |
\begin{lstlisting}[numbers=none] |
|
398 |
scala> res0 + 4 |
|
399 |
res1: Int = 9 |
|
400 |
\end{lstlisting} |
|
401 |
||
402 |
\noindent |
|
403 |
Another classic example you can try out is |
|
123 | 404 |
|
405 |
\begin{lstlisting}[numbers=none] |
|
406 |
scala> print("hello world") |
|
407 |
hello world |
|
408 |
\end{lstlisting} |
|
409 |
||
410 |
\noindent Note that in this case there is no result. The |
|
411 |
reason is that \code{print} does not actually produce a result |
|
124 | 412 |
(there is no \code{resX} and no type), rather it is a |
123 | 413 |
function that causes the \emph{side-effect} of printing out a |
414 |
string. Once you are more familiar with the functional |
|
415 |
programming-style, you will know what the difference is |
|
416 |
between a function that returns a result, like addition, and a |
|
417 |
function that causes a side-effect, like \code{print}. We |
|
418 |
shall come back to this point later, but if you are curious |
|
419 |
now, the latter kind of functions always has \code{Unit} as |
|
188 | 420 |
return type. It is just not printed by Scala. |
123 | 421 |
|
181 | 422 |
You can try more examples with the Scala REPL, but feel free to |
423 |
first guess what the result is (not all answers by Scala are obvious): |
|
123 | 424 |
|
425 |
\begin{lstlisting}[numbers=none] |
|
426 |
scala> 2 + 2 |
|
427 |
scala> 1 / 2 |
|
428 |
scala> 1.0 / 2 |
|
429 |
scala> 1 / 2.0 |
|
430 |
scala> 1 / 0 |
|
431 |
scala> 1.0 / 0.0 |
|
432 |
scala> true == false |
|
433 |
scala> true && false |
|
434 |
scala> 1 > 1.0 |
|
435 |
scala> "12345".length |
|
181 | 436 |
scala> List(1,2,1).size |
437 |
scala> Set(1,2,1).size |
|
265 | 438 |
scala> List(1) == List(1) |
439 |
scala> Array(1) == Array(1) |
|
440 |
scala> Array(1).sameElements(Array(1)) |
|
181 | 441 |
\end{lstlisting}\smallskip |
123 | 442 |
|
181 | 443 |
\noindent |
444 |
Please take the Scala REPL seriously: If you want to take advantage of my |
|
445 |
reference implementation for the assignments, you will need to be |
|
446 |
able to ``play around'' with it! |
|
447 |
||
448 |
\subsection*{Standalone Scala Apps} |
|
123 | 449 |
|
450 |
If you want to write a stand-alone app in Scala, you can |
|
197 | 451 |
implement an object that is an instance of \code{App}. For example |
452 |
write |
|
123 | 453 |
|
454 |
\begin{lstlisting}[numbers=none] |
|
455 |
object Hello extends App { |
|
456 |
println("hello world") |
|
457 |
} |
|
458 |
\end{lstlisting} |
|
459 |
||
197 | 460 |
\noindent save it in a file, say {\tt hello-world.scala}, and |
188 | 461 |
then run the compiler (\texttt{scalac}) and start the runtime |
181 | 462 |
environment (\texttt{scala}): |
123 | 463 |
|
464 |
\begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small] |
|
465 |
$ scalac hello-world.scala |
|
466 |
$ scala Hello |
|
467 |
hello world |
|
468 |
\end{lstlisting} |
|
469 |
||
124 | 470 |
\noindent |
123 | 471 |
Like Java, Scala targets the JVM and consequently |
472 |
Scala programs can also be executed by the bog-standard Java |
|
473 |
Runtime. This only requires the inclusion of {\tt |
|
474 |
scala-library.jar}, which on my computer can be done as |
|
475 |
follows: |
|
476 |
||
477 |
\begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small] |
|
478 |
$ scalac hello-world.scala |
|
479 |
$ java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello |
|
480 |
hello world |
|
481 |
\end{lstlisting} |
|
482 |
||
483 |
\noindent You might need to adapt the path to where you have |
|
484 |
installed Scala. |
|
485 |
||
486 |
\subsection*{Values} |
|
487 |
||
124 | 488 |
In the lectures I will try to avoid as much as possible the term |
489 |
\emph{variables} familiar from other programming languages. The reason |
|
490 |
is that Scala has \emph{values}, which can be seen as abbreviations of |
|
491 |
larger expressions. For example |
|
123 | 492 |
|
493 |
\begin{lstlisting}[numbers=none] |
|
494 |
scala> val x = 42 |
|
495 |
x: Int = 42 |
|
496 |
||
497 |
scala> val y = 3 + 4 |
|
498 |
y: Int = 7 |
|
499 |
||
500 |
scala> val z = x / y |
|
501 |
z: Int = 6 |
|
502 |
\end{lstlisting} |
|
503 |
||
504 |
\noindent |
|
181 | 505 |
Why the kerfuffle about values? Well, values are \emph{immutable}. You |
506 |
cannot change their value after you defined them. If you try to reassign |
|
124 | 507 |
\code{z} above, Scala will yell at you: |
123 | 508 |
|
509 |
\begin{lstlisting}[numbers=none] |
|
510 |
scala> z = 9 |
|
511 |
error: reassignment to val |
|
512 |
z = 9 |
|
513 |
^ |
|
514 |
\end{lstlisting} |
|
515 |
||
516 |
\noindent |
|
517 |
So it would be a bit absurd to call values as variables...you cannot |
|
195 | 518 |
change them; they cannot vary. You might think you can reassign them like |
123 | 519 |
|
520 |
\begin{lstlisting}[numbers=none] |
|
521 |
scala> val x = 42 |
|
522 |
scala> val z = x / 7 |
|
523 |
scala> val x = 70 |
|
524 |
scala> println(z) |
|
525 |
\end{lstlisting} |
|
526 |
||
124 | 527 |
\noindent but try to guess what Scala will print out |
123 | 528 |
for \code{z}? Will it be \code{6} or \code{10}? A final word about |
529 |
values: Try to stick to the convention that names of values should be |
|
188 | 530 |
lower case, like \code{x}, \code{y}, \code{foo41} and so on. Upper-case |
531 |
names you should reserve for what is called \emph{constructors}. |
|
123 | 532 |
|
533 |
||
534 |
\subsection*{Function Definitions} |
|
535 |
||
181 | 536 |
We do functional programming! So defining functions will be our main occupation. |
182 | 537 |
As an example, a function named \code{f} taking a single argument of type |
181 | 538 |
\code{Int} can be defined in Scala as follows: |
123 | 539 |
|
540 |
\begin{lstlisting}[numbers=none] |
|
181 | 541 |
def f(x: Int) : String = ...EXPR... |
123 | 542 |
\end{lstlisting} |
543 |
||
544 |
\noindent |
|
124 | 545 |
This function returns the value resulting from evaluating the expression |
123 | 546 |
\code{EXPR} (whatever is substituted for this). The result will be |
197 | 547 |
of type \code{String}. It is a good habit to always include this information |
548 |
about the return type. Simple examples of Scala functions are: |
|
123 | 549 |
|
550 |
\begin{lstlisting}[numbers=none] |
|
551 |
def incr(x: Int) : Int = x + 1 |
|
552 |
def double(x: Int) : Int = x + x |
|
553 |
def square(x: Int) : Int = x * x |
|
554 |
\end{lstlisting} |
|
555 |
||
556 |
\noindent |
|
557 |
The general scheme for a function is |
|
558 |
||
559 |
\begin{lstlisting}[numbers=none] |
|
560 |
def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = { |
|
561 |
BODY |
|
562 |
} |
|
563 |
\end{lstlisting} |
|
564 |
||
565 |
\noindent |
|
197 | 566 |
where each argument, \texttt{arg1}, \texttt{arg2} and so on, requires |
567 |
its type and the result type of the |
|
568 |
function, \code{rty}, should also be given. If the body of the function is |
|
124 | 569 |
more complex, then it can be enclosed in braces, like above. If it it |
570 |
is just a simple expression, like \code{x + 1}, you can omit the |
|
195 | 571 |
braces. Very often functions are recursive (that is call themselves), |
572 |
like the venerable factorial function: |
|
123 | 573 |
|
574 |
\begin{lstlisting}[numbers=none] |
|
575 |
def fact(n: Int): Int = |
|
576 |
if (n == 0) 1 else n * fact(n - 1) |
|
577 |
\end{lstlisting} |
|
188 | 578 |
|
579 |
\noindent |
|
580 |
Note that Scala does not have a \code{then}-keyword in an \code{if}-statement. |
|
123 | 581 |
|
582 |
\subsection*{Loops, or better the Absence thereof} |
|
583 |
||
584 |
Coming from Java or C++, you might be surprised that Scala does |
|
585 |
not really have loops. It has instead, what is in functional |
|
586 |
programming called, \emph{maps}. To illustrate how they work, |
|
587 |
let us assume you have a list of numbers from 1 to 8 and want to |
|
588 |
build the list of squares. The list of numbers from 1 to 8 |
|
589 |
can be constructed in Scala as follows: |
|
590 |
||
591 |
\begin{lstlisting}[numbers=none] |
|
592 |
scala> (1 to 8).toList |
|
593 |
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8) |
|
594 |
\end{lstlisting} |
|
595 |
||
197 | 596 |
\noindent Generating from this list the list of corresponding |
597 |
squares in a programming language such as Java, you would assume |
|
598 |
the list is given as a kind of array. You would then iterate, or loop, |
|
123 | 599 |
an index over this array and replace each entry in the array |
600 |
by the square. Right? In Scala, and in other functional |
|
601 |
programming languages, you use maps to achieve the same. |
|
602 |
||
603 |
A map essentially takes a function that describes how each |
|
604 |
element is transformed (for example squared) and a list over |
|
605 |
which this function should work. There are two forms to |
|
606 |
express such maps in Scala. The first way is called a |
|
607 |
\emph{for-comprehension}. Squaring the numbers from 1 to 8 |
|
608 |
would look as follows: |
|
609 |
||
610 |
\begin{lstlisting}[numbers=none] |
|
611 |
scala> for (n <- (1 to 8).toList) yield n * n |
|
612 |
res2: List[Int] = List(1, 4, 9, 16, 25, 36, 49, 64) |
|
613 |
\end{lstlisting} |
|
614 |
||
615 |
\noindent The important keywords are \code{for} and |
|
616 |
\code{yield}. This for-comprehension roughly states that from |
|
197 | 617 |
the list of numbers we draw elements that are given the name |
618 |
\code{n} and compute the result |
|
619 |
of \code{n * n}. This is a simple example---what comes after |
|
620 |
\code{yield} can be a complex expression enclosed in \texttt{\{...\}}. |
|
621 |
As you can see, we specified the list where |
|
123 | 622 |
each \code{n} comes from, namely \code{(1 to 8).toList}, and |
623 |
how each element needs to be transformed. This can also be |
|
624 |
expressed in a second way in Scala by using directly |
|
625 |
\code{map}s as follows: |
|
626 |
||
627 |
\begin{lstlisting}[numbers=none] |
|
628 |
scala> (1 to 8).toList.map(n => n * n) |
|
629 |
res3 = List(1, 4, 9, 16, 25, 36, 49, 64) |
|
630 |
\end{lstlisting} |
|
631 |
||
632 |
\noindent In this way, the expression \code{n => n * n} stands |
|
633 |
for the function that calculates the square (this is how the |
|
634 |
\code{n}s are transformed). This expression for functions |
|
635 |
might remind you of your lessons about the lambda-calculus |
|
636 |
where this would have been written as $\lambda n.\,n * n$. It |
|
637 |
might not be obvious, but for-comprehensions are just |
|
638 |
syntactic sugar: when compiling, Scala translates |
|
639 |
for-comprehensions into equivalent maps. This even works |
|
640 |
when for-comprehensions get more complicated (see below). |
|
641 |
||
642 |
The very charming feature of Scala is that such maps or |
|
643 |
for-comprehensions can be written for any kind of data |
|
644 |
collection, such as lists, sets, vectors, options and so on. |
|
270
b9eaa5cdec4a
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
269
diff
changeset
|
645 |
For example if we instead compute the remainders modulo 3 of |
123 | 646 |
this list, we can write |
647 |
||
648 |
\begin{lstlisting}[numbers=none] |
|
649 |
scala> (1 to 8).toList.map(n => n % 3) |
|
650 |
res4 = List(1, 2, 0, 1, 2, 0, 1, 2) |
|
651 |
\end{lstlisting} |
|
652 |
||
653 |
\noindent If we, however, transform the numbers 1 to 8 not |
|
270
b9eaa5cdec4a
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
269
diff
changeset
|
654 |
into a list, but into a set, and then compute the remainders |
123 | 655 |
modulo 3 we obtain |
656 |
||
657 |
\begin{lstlisting}[numbers=none] |
|
658 |
scala> (1 to 8).toSet[Int].map(n => n % 3) |
|
659 |
res5 = Set(2, 1, 0) |
|
660 |
\end{lstlisting} |
|
661 |
||
662 |
\noindent This is the correct result for sets, as there are |
|
663 |
only three equivalence classes of integers modulo 3. Note that |
|
664 |
in this example we need to ``help'' Scala to transform the |
|
665 |
numbers into a set of integers by explicitly annotating the |
|
666 |
type \code{Int}. Since maps and for-comprehensions are |
|
667 |
just syntactic variants of each other, the latter can also be |
|
668 |
written as |
|
669 |
||
670 |
\begin{lstlisting}[numbers=none] |
|
671 |
scala> for (n <- (1 to 8).toSet[Int]) yield n % 3 |
|
672 |
res5 = Set(2, 1, 0) |
|
673 |
\end{lstlisting} |
|
674 |
||
675 |
For-comprehensions can also be nested and the selection of |
|
676 |
elements can be guarded. For example if we want to pair up |
|
677 |
the numbers 1 to 4 with the letters a to c, we can write |
|
678 |
||
679 |
\begin{lstlisting}[numbers=none] |
|
680 |
scala> for (n <- (1 to 4).toList; |
|
681 |
m <- ('a' to 'c').toList) yield (n, m) |
|
682 |
res6 = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c), |
|
683 |
(3,a), (3,b), (3,c), (4,a), (4,b), (4,c)) |
|
684 |
\end{lstlisting} |
|
685 |
||
686 |
\noindent |
|
687 |
Or if we want to find all pairs of numbers between 1 and 3 |
|
688 |
where the sum is an even number, we can write |
|
689 |
||
690 |
\begin{lstlisting}[numbers=none] |
|
691 |
scala> for (n <- (1 to 3).toList; |
|
692 |
m <- (1 to 3).toList; |
|
693 |
if (n + m) % 2 == 0) yield (n, m) |
|
694 |
res7 = List((1,1), (1,3), (2,2), (3,1), (3,3)) |
|
695 |
\end{lstlisting} |
|
696 |
||
697 |
\noindent The \code{if}-condition in the for-comprehension |
|
698 |
filters out all pairs where the sum is not even. |
|
699 |
||
700 |
While hopefully this all looks reasonable, there is one |
|
701 |
complication: In the examples above we always wanted to |
|
702 |
transform one list into another list (e.g.~list of squares), |
|
703 |
or one set into another set (set of numbers into set of |
|
270
b9eaa5cdec4a
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
269
diff
changeset
|
704 |
remainders modulo 3). What happens if we just want to print out |
123 | 705 |
a list of integers? Then actually the for-comprehension |
706 |
needs to be modified. The reason is that \code{print}, you |
|
707 |
guessed it, does not produce any result, but only produces |
|
708 |
what is in the functional-programming-lingo called a |
|
197 | 709 |
\emph{side-effect}. Printing out the list of numbers from 1 to 5 |
123 | 710 |
would look as follows |
711 |
||
712 |
\begin{lstlisting}[numbers=none] |
|
713 |
scala> for (n <- (1 to 5).toList) print(n) |
|
714 |
12345 |
|
715 |
\end{lstlisting} |
|
716 |
||
717 |
\noindent |
|
718 |
where you need to omit the keyword \code{yield}. You can |
|
719 |
also do more elaborate calculations such as |
|
720 |
||
721 |
\begin{lstlisting}[numbers=none] |
|
722 |
scala> for (n <- (1 to 5).toList) { |
|
197 | 723 |
val square = n * n |
724 |
println(s"$n * $n = $square") |
|
123 | 725 |
} |
726 |
1 * 1 = 1 |
|
727 |
2 * 2 = 4 |
|
728 |
3 * 3 = 9 |
|
729 |
4 * 4 = 16 |
|
730 |
5 * 5 = 25 |
|
731 |
\end{lstlisting}%$ |
|
732 |
||
733 |
\noindent In this code I use a variable assignment (\code{val |
|
197 | 734 |
square = ...} ) and also what is called in Scala a |
123 | 735 |
\emph{string interpolation}, written \code{s"..."}. The latter |
736 |
is for printing out an equation. It allows me to refer to the |
|
270
b9eaa5cdec4a
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
269
diff
changeset
|
737 |
integer values \code{n} and \code{square} inside a string. |
123 | 738 |
This is very convenient for printing out ``things''. |
739 |
||
740 |
The corresponding map construction for functions with |
|
741 |
side-effects is in Scala called \code{foreach}. So you |
|
742 |
could also write |
|
743 |
||
744 |
||
745 |
\begin{lstlisting}[numbers=none] |
|
746 |
scala> (1 to 5).toList.foreach(n => print(n)) |
|
747 |
12345 |
|
748 |
\end{lstlisting} |
|
749 |
||
750 |
||
751 |
\noindent or even just |
|
752 |
||
753 |
\begin{lstlisting}[numbers=none] |
|
754 |
scala> (1 to 5).toList.foreach(print) |
|
755 |
12345 |
|
756 |
\end{lstlisting} |
|
757 |
||
758 |
\noindent Again I hope this reminds you a bit of your |
|
759 |
lambda-calculus lessons, where an explanation is given why |
|
760 |
both forms produce the same result. |
|
761 |
||
762 |
||
763 |
If you want to find out more about maps and functions with |
|
764 |
side-effects, you can ponder about the response Scala gives if |
|
765 |
you replace \code{foreach} by \code{map} in the expression |
|
766 |
above. Scala will still allow \code{map} with side-effect |
|
767 |
functions, but then reacts with a slightly interesting result. |
|
768 |
||
769 |
\subsection*{Types} |
|
770 |
||
771 |
In most functional programming languages, types play an |
|
772 |
important role. Scala is such a language. You have already |
|
773 |
seen built-in types, like \code{Int}, \code{Boolean}, |
|
774 |
\code{String} and \code{BigInt}, but also user-defined ones, |
|
195 | 775 |
like \code{Rexp} (see coursework). Unfortunately, types can be a thorny |
123 | 776 |
subject, especially in Scala. For example, why do we need to |
777 |
give the type to \code{toSet[Int]}, but not to \code{toList}? |
|
778 |
The reason is the power of Scala, which sometimes means it |
|
779 |
cannot infer all necessary typing information. At the |
|
195 | 780 |
beginning, while getting familiar with Scala, I recommend a |
123 | 781 |
``play-it-by-ear-approach'' to types. Fully understanding |
782 |
type-systems, especially complicated ones like in Scala, can |
|
783 |
take a module on their own.\footnote{Still, such a study can |
|
784 |
be a rewarding training: If you are in the business of |
|
785 |
designing new programming languages, you will not be able to |
|
786 |
turn a blind eye to types. They essentially help programmers |
|
787 |
to avoid common programming errors and help with maintaining |
|
788 |
code.} |
|
789 |
||
790 |
In Scala, types are needed whenever you define an inductive |
|
791 |
datatype and also whenever you define functions (their |
|
792 |
arguments and their results need a type). Base types are types |
|
793 |
that do not take any (type)arguments, for example \code{Int} |
|
794 |
and \code{String}. Compound types take one or more arguments, |
|
795 |
which as seen earlier need to be given in angle-brackets, for |
|
796 |
example \code{List[Int]} or \code{Set[List[String]]} or |
|
797 |
\code{Map[Int, Int]}. |
|
798 |
||
799 |
There are a few special type-constructors that fall outside |
|
800 |
this pattern. One is for tuples, where the type is written |
|
801 |
with parentheses. For example |
|
802 |
||
803 |
\begin{lstlisting}[ numbers=none] |
|
804 |
(Int, Int, String) |
|
805 |
\end{lstlisting} |
|
806 |
||
807 |
\noindent is for a triple (a tuple with three components---two |
|
808 |
integers and a string). Tuples are helpful if you want to |
|
809 |
define functions with multiple results, say the function |
|
270
b9eaa5cdec4a
updated
Christian Urban <christian dot urban at kcl dot ac dot uk>
parents:
269
diff
changeset
|
810 |
returning the quotient and remainder of two numbers. For this |
123 | 811 |
you might define: |
812 |
||
813 |
||
814 |
\begin{lstlisting}[ numbers=none] |
|
815 |
def quo_rem(m: Int, n: Int) : (Int, Int) = (m / n, m % n) |
|
816 |
\end{lstlisting} |
|
817 |
||
818 |
||
819 |
\noindent Since this function returns a pair of integers, its |
|
820 |
return type needs to be of type \code{(Int, Int)}. |
|
821 |
Incidentally, this is also the input type of this function. |
|
822 |
Notice this function takes \emph{two} arguments, namely |
|
823 |
\code{m} and \code{n}, both of which are integers. They are |
|
824 |
``packaged'' in a pair. Consequently the complete type of |
|
825 |
\code{quo_rem} is |
|
826 |
||
827 |
\begin{lstlisting}[ numbers=none] |
|
828 |
(Int, Int) => (Int, Int) |
|
829 |
\end{lstlisting} |
|
830 |
||
831 |
Another special type-constructor is for functions, written as |
|
832 |
the arrow \code{=>}. For example, the type \code{Int => |
|
833 |
String} is for a function that takes an integer as input |
|
834 |
argument and produces a string as result. A function of this |
|
835 |
type is for instance |
|
836 |
||
837 |
\begin{lstlisting}[numbers=none] |
|
838 |
def mk_string(n: Int) : String = n match { |
|
839 |
case 0 => "zero" |
|
840 |
case 1 => "one" |
|
841 |
case 2 => "two" |
|
842 |
case _ => "many" |
|
843 |
} |
|
844 |
\end{lstlisting} |
|
845 |
||
846 |
\noindent It takes an integer as input argument and returns a |
|
847 |
string. Unlike other functional programming languages, there |
|
848 |
is in Scala no easy way to find out the types of existing |
|
849 |
functions, except by looking into the documentation |
|
850 |
||
851 |
\begin{quote} |
|
852 |
\url{http://www.scala-lang.org/api/current/} |
|
853 |
\end{quote} |
|
854 |
||
855 |
The function arrow can also be iterated, as in |
|
856 |
\code{Int => String => Boolean}. This is the type for a function |
|
857 |
taking an integer as first argument and a string as second, |
|
858 |
and the result of the function is a boolean. Though silly, a |
|
859 |
function of this type would be |
|
860 |
||
861 |
||
862 |
\begin{lstlisting}[numbers=none] |
|
863 |
def chk_string(n: Int)(s: String) : Boolean = |
|
864 |
mk_string(n) == s |
|
865 |
\end{lstlisting} |
|
866 |
||
867 |
||
868 |
\noindent which checks whether the integer \code{n} |
|
869 |
corresponds to the name \code{s} given by the function |
|
870 |
\code{mk\_string}. Notice the unusual way of specifying the |
|
871 |
arguments of this function: the arguments are given one after |
|
872 |
the other, instead of being in a pair (what would be the type |
|
873 |
of this function then?). This way of specifying the arguments |
|
874 |
can be useful, for example in situations like this |
|
875 |
||
876 |
\begin{lstlisting}[numbers=none] |
|
877 |
scala> List("one", "two", "three", "many").map(chk_string(2)) |
|
878 |
res4 = List(false, true, false, false) |
|
879 |
||
880 |
scala> List("one", "two", "three", "many").map(chk_string(3)) |
|
881 |
res5 = List(false, false, false, true) |
|
882 |
\end{lstlisting} |
|
883 |
||
884 |
\noindent In each case we can give to \code{map} a specialised |
|
885 |
version of \code{chk_string}---once specialised to 2 and once |
|
886 |
to 3. This kind of ``specialising'' a function is called |
|
887 |
\emph{partial application}---we have not yet given to this |
|
888 |
function all arguments it needs, but only some of them. |
|
889 |
||
890 |
Coming back to the type \code{Int => String => Boolean}. The |
|
891 |
rule about such function types is that the right-most type |
|
892 |
specifies what the function returns (a boolean in this case). |
|
893 |
The types before that specify how many arguments the function |
|
894 |
expects and what their type is (in this case two arguments, |
|
895 |
one of type \code{Int} and another of type \code{String}). |
|
896 |
Given this rule, what kind of function has type |
|
897 |
\mbox{\code{(Int => String) => Boolean}}? Well, it returns a |
|
898 |
boolean. More interestingly, though, it only takes a single |
|
899 |
argument (because of the parentheses). The single argument |
|
900 |
happens to be another function (taking an integer as input and |
|
901 |
returning a string). Remember that \code{mk_string} is just |
|
902 |
such a function. So how can we use it? For this define |
|
903 |
the somewhat silly function \code{apply_3}: |
|
904 |
||
905 |
\begin{lstlisting}[numbers=none] |
|
906 |
def apply_3(f: Int => String): Bool = f(3) == "many" |
|
907 |
||
908 |
scala> apply_3(mk_string) |
|
909 |
res6 = true |
|
910 |
\end{lstlisting} |
|
911 |
||
912 |
You might ask: Apart from silly functions like above, what is |
|
913 |
the point of having functions as input arguments to other |
|
914 |
functions? In Java there is indeed no need of this kind of |
|
915 |
feature: at least in the past it did not allow such |
|
197 | 916 |
constructions. I think, the point of Java 8 and successors was to lift this |
123 | 917 |
restriction. But in all functional programming languages, |
918 |
including Scala, it is really essential to allow functions as |
|
919 |
input argument. Above you already seen \code{map} and |
|
920 |
\code{foreach} which need this. Consider the functions |
|
921 |
\code{print} and \code{println}, which both print out strings, |
|
922 |
but the latter adds a line break. You can call \code{foreach} |
|
923 |
with either of them and thus changing how, for example, five |
|
924 |
numbers are printed. |
|
925 |
||
926 |
||
927 |
\begin{lstlisting}[numbers=none] |
|
928 |
scala> (1 to 5).toList.foreach(print) |
|
929 |
12345 |
|
930 |
scala> (1 to 5).toList.foreach(println) |
|
931 |
1 |
|
932 |
2 |
|
933 |
3 |
|
934 |
4 |
|
935 |
5 |
|
936 |
\end{lstlisting} |
|
937 |
||
938 |
||
939 |
\noindent This is actually one of the main design principles |
|
940 |
in functional programming. You have generic functions like |
|
941 |
\code{map} and \code{foreach} that can traverse data containers, |
|
942 |
like lists or sets. They then take a function to specify what |
|
943 |
should be done with each element during the traversal. This |
|
944 |
requires that the generic traversal functions can cope with |
|
945 |
any kind of function (not just functions that, for example, |
|
946 |
take as input an integer and produce a string like above). |
|
947 |
This means we cannot fix the type of the generic traversal |
|
948 |
functions, but have to keep them |
|
181 | 949 |
\emph{polymorphic}.\footnote{Another interesting topic about |
123 | 950 |
types, but we omit it here for the sake of brevity.} |
951 |
||
952 |
There is one more type constructor that is rather special. It |
|
953 |
is called \code{Unit}. Recall that \code{Boolean} has two |
|
954 |
values, namely \code{true} and \code{false}. This can be used, |
|
955 |
for example, to test something and decide whether the test |
|
956 |
succeeds or not. In contrast the type \code{Unit} has only a |
|
957 |
single value, written \code{()}. This seems like a completely |
|
958 |
useless type and return value for a function, but is actually |
|
959 |
quite useful. It indicates when the function does not return |
|
960 |
any result. The purpose of these functions is to cause |
|
961 |
something being written on the screen or written into a file, |
|
962 |
for example. This is what is called they cause some effect on |
|
963 |
the side, namely a new content displayed on the screen or some |
|
964 |
new data in a file. Scala uses the \code{Unit} type to indicate |
|
965 |
that a function does not have a result, but potentially causes |
|
966 |
some side-effect. Typical examples are the printing functions, |
|
967 |
like \code{print}. |
|
968 |
||
969 |
||
143 | 970 |
% \subsection*{Cool Stuff} |
123 | 971 |
|
143 | 972 |
% The first wow-moment I had with Scala was when I came across |
973 |
% the following code-snippet for reading a web-page. |
|
123 | 974 |
|
975 |
||
143 | 976 |
% \begin{lstlisting}[ numbers=none] |
977 |
% import io.Source |
|
978 |
% val url = """http://www.inf.kcl.ac.uk/staff/urbanc/""" |
|
979 |
% Source.fromURL(url)("ISO-8859-1").take(10000).mkString |
|
980 |
% \end{lstlisting} |
|
123 | 981 |
|
982 |
||
143 | 983 |
% \noindent These three lines return a string containing the |
984 |
% HTML-code of my webpage. It actually already does something |
|
985 |
% more sophisticated, namely only returns the first 10000 |
|
986 |
% characters of a webpage in case it is too large. Why is that |
|
987 |
% code-snippet of any interest? Well, try implementing |
|
988 |
% reading-from-a-webpage in Java. I also like the possibility of |
|
989 |
% triple-quoting strings, which I have only seen in Scala so |
|
990 |
% far. The idea behind this is that in such a string all |
|
991 |
% characters are interpreted literally---there are no escaped |
|
992 |
% characters, like \verb|\n| for newlines. |
|
123 | 993 |
|
143 | 994 |
% My second wow-moment I had with a feature of Scala that other |
995 |
% functional programming languages do not have. This feature is |
|
996 |
% about implicit type conversions. If you have regular |
|
997 |
% expressions and want to use them for language processing you |
|
998 |
% often want to recognise keywords in a language, for example |
|
999 |
% \code{for},{} \code{if},{} \code{yield} and so on. But the |
|
1000 |
% basic regular expression \code{CHAR} can only recognise a |
|
1001 |
% single character. In order to recognise a whole string, like |
|
1002 |
% \code{for}, you have to put many of those together using |
|
1003 |
% \code{SEQ}: |
|
123 | 1004 |
|
1005 |
||
143 | 1006 |
% \begin{lstlisting}[numbers=none] |
1007 |
% SEQ(CHAR('f'), SEQ(CHAR('o'), CHAR('r'))) |
|
1008 |
% \end{lstlisting} |
|
123 | 1009 |
|
143 | 1010 |
% \noindent This gets quickly unreadable when the strings and |
1011 |
% regular expressions get more complicated. In other functional |
|
1012 |
% programming languages, you can explicitly write a conversion |
|
1013 |
% function that takes a string, say \dq{\pcode{for}}, and |
|
1014 |
% generates the regular expression above. But then your code is |
|
1015 |
% littered with such conversion functions. |
|
123 | 1016 |
|
143 | 1017 |
% In Scala you can do better by ``hiding'' the conversion |
1018 |
% functions. The keyword for doing this is \code{implicit} and |
|
1019 |
% it needs a built-in library called |
|
123 | 1020 |
|
143 | 1021 |
% \begin{lstlisting}[numbers=none] |
1022 |
% scala.language.implicitConversions |
|
1023 |
% \end{lstlisting} |
|
123 | 1024 |
|
143 | 1025 |
% \noindent |
1026 |
% Consider the code |
|
123 | 1027 |
|
1028 |
||
143 | 1029 |
% \begin{lstlisting}[language=Scala] |
1030 |
% import scala.language.implicitConversions |
|
123 | 1031 |
|
143 | 1032 |
% def charlist2rexp(s: List[Char]) : Rexp = s match { |
1033 |
% case Nil => EMPTY |
|
1034 |
% case c::Nil => CHAR(c) |
|
1035 |
% case c::s => SEQ(CHAR(c), charlist2rexp(s)) |
|
1036 |
% } |
|
123 | 1037 |
|
143 | 1038 |
% implicit def string2rexp(s: String) : Rexp = |
1039 |
% charlist2rexp(s.toList) |
|
1040 |
% \end{lstlisting} |
|
123 | 1041 |
|
1042 |
||
143 | 1043 |
% \noindent where the first seven lines implement a function |
1044 |
% that given a list of characters generates the corresponding |
|
1045 |
% regular expression. In Lines 9 and 10, this function is used |
|
1046 |
% for transforming a string into a regular expression. Since the |
|
1047 |
% \code{string2rexp}-function is declared as \code{implicit}, |
|
1048 |
% the effect will be that whenever Scala expects a regular |
|
1049 |
% expression, but I only give it a string, it will automatically |
|
1050 |
% insert a call to the \code{string2rexp}-function. I can now |
|
1051 |
% write for example |
|
123 | 1052 |
|
143 | 1053 |
% \begin{lstlisting}[numbers=none] |
1054 |
% scala> ALT("ab", "ac") |
|
1055 |
% res9 = ALT(SEQ(CHAR(a),CHAR(b)),SEQ(CHAR(a),CHAR(c))) |
|
1056 |
% \end{lstlisting} |
|
123 | 1057 |
|
143 | 1058 |
% \noindent Recall that \code{ALT} expects two regular |
1059 |
% expressions as arguments, but I only supply two strings. The |
|
1060 |
% implicit conversion function will transform the string into a |
|
1061 |
% regular expression. |
|
123 | 1062 |
|
143 | 1063 |
% Using implicit definitions, Scala allows me to introduce |
1064 |
% some further syntactic sugar for regular expressions: |
|
123 | 1065 |
|
1066 |
||
143 | 1067 |
% \begin{lstlisting}[ numbers=none] |
1068 |
% implicit def RexpOps(r: Rexp) = new { |
|
1069 |
% def | (s: Rexp) = ALT(r, s) |
|
1070 |
% def ~ (s: Rexp) = SEQ(r, s) |
|
1071 |
% def % = STAR(r) |
|
1072 |
% } |
|
123 | 1073 |
|
143 | 1074 |
% implicit def stringOps(s: String) = new { |
1075 |
% def | (r: Rexp) = ALT(s, r) |
|
1076 |
% def | (r: String) = ALT(s, r) |
|
1077 |
% def ~ (r: Rexp) = SEQ(s, r) |
|
1078 |
% def ~ (r: String) = SEQ(s, r) |
|
1079 |
% def % = STAR(s) |
|
1080 |
% } |
|
1081 |
% \end{lstlisting} |
|
123 | 1082 |
|
1083 |
||
143 | 1084 |
% \noindent This might seem a bit overly complicated, but its effect is |
1085 |
% that I can now write regular expressions such as $ab + ac$ |
|
1086 |
% simply as |
|
123 | 1087 |
|
1088 |
||
143 | 1089 |
% \begin{lstlisting}[numbers=none] |
1090 |
% scala> "ab" | "ac" |
|
1091 |
% res10 = ALT(SEQ(CHAR(a),CHAR(b)),SEQ(CHAR(a),CHAR(c))) |
|
1092 |
% \end{lstlisting} |
|
123 | 1093 |
|
1094 |
||
143 | 1095 |
% \noindent I leave you to figure out what the other |
1096 |
% syntactic sugar in the code above stands for. |
|
123 | 1097 |
|
143 | 1098 |
% One more useful feature of Scala is the ability to define |
1099 |
% functions with varying argument lists. This is a feature that |
|
1100 |
% is already present in old languages, like C, but seems to have |
|
1101 |
% been forgotten in the meantime---Java does not have it. In the |
|
1102 |
% context of regular expressions this feature comes in handy: |
|
1103 |
% Say you are fed up with writing many alternatives as |
|
123 | 1104 |
|
1105 |
||
143 | 1106 |
% \begin{lstlisting}[numbers=none] |
1107 |
% ALT(..., ALT(..., ALT(..., ...))) |
|
1108 |
% \end{lstlisting} |
|
123 | 1109 |
|
1110 |
||
143 | 1111 |
% \noindent To make it difficult, you do not know how deep such |
1112 |
% alternatives are nested. So you need something flexible that |
|
1113 |
% can take as many alternatives as needed. In Scala one can |
|
1114 |
% achieve this by adding a \code{*} to the type of an argument. |
|
1115 |
% Consider the code |
|
123 | 1116 |
|
1117 |
||
143 | 1118 |
% \begin{lstlisting}[language=Scala] |
1119 |
% def Alts(rs: List[Rexp]) : Rexp = rs match { |
|
1120 |
% case Nil => NULL |
|
1121 |
% case r::Nil => r |
|
1122 |
% case r::rs => ALT(r, Alts(rs)) |
|
1123 |
% } |
|
123 | 1124 |
|
143 | 1125 |
% def ALTS(rs: Rexp*) = Alts(rs.toList) |
1126 |
% \end{lstlisting} |
|
123 | 1127 |
|
1128 |
||
143 | 1129 |
% \noindent The function in Lines 1 to 5 takes a list of regular |
1130 |
% expressions and converts it into an appropriate alternative |
|
1131 |
% regular expression. In Line 7 there is a wrapper for this |
|
1132 |
% function which uses the feature of varying argument lists. The |
|
1133 |
% effect of this code is that I can write the regular |
|
1134 |
% expression for keywords as |
|
123 | 1135 |
|
1136 |
||
143 | 1137 |
% \begin{lstlisting}[numbers=none] |
1138 |
% ALTS("for", "def", "yield", "implicit", "if", "match", "case") |
|
1139 |
% \end{lstlisting} |
|
123 | 1140 |
|
1141 |
||
143 | 1142 |
% \noindent Again I leave it to you to find out how much this |
1143 |
% simplifies the regular expression in comparison with if I had |
|
1144 |
% to write this by hand using only the ``plain'' regular |
|
1145 |
% expressions from the inductive datatype. |
|
1146 |
||
197 | 1147 |
%\bigskip\noindent |
1148 |
%\textit{More TBD.} |
|
123 | 1149 |
|
197 | 1150 |
%\subsection*{Coursework} |
181 | 1151 |
|
195 | 1152 |
|
1153 |
||
123 | 1154 |
\subsection*{More Info} |
1155 |
||
1156 |
There is much more to Scala than I can possibly describe in |
|
197 | 1157 |
this document and teach in the lectures. Fortunately there are a |
1158 |
number of free books |
|
123 | 1159 |
about Scala and of course lots of help online. For example |
1160 |
||
1161 |
\begin{itemize} |
|
1162 |
\item \url{http://www.scala-lang.org/docu/files/ScalaByExample.pdf} |
|
1163 |
\item \url{http://www.scala-lang.org/docu/files/ScalaTutorial.pdf} |
|
1164 |
\item \url{https://www.youtube.com/user/ShadowofCatron} |
|
1165 |
\item \url{http://docs.scala-lang.org/tutorials} |
|
1166 |
\item \url{https://www.scala-exercises.org} |
|
188 | 1167 |
\item \url{https://twitter.github.io/scala_school} |
123 | 1168 |
\end{itemize} |
188 | 1169 |
|
197 | 1170 |
\noindent There is also an online course at Coursera on Functional |
123 | 1171 |
Programming Principles in Scala by Martin Odersky, the main |
1172 |
developer of the Scala language. And a document that explains |
|
1173 |
Scala for Java programmers |
|
1174 |
||
1175 |
\begin{itemize} |
|
1176 |
\item \small\url{http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html} |
|
1177 |
\end{itemize} |
|
1178 |
||
1179 |
While I am quite enthusiastic about Scala, I am also happy to |
|
1180 |
admit that it has more than its fair share of faults. The |
|
1181 |
problem seen earlier of having to give an explicit type to |
|
1182 |
\code{toSet}, but not \code{toList} is one of them. There are |
|
1183 |
also many ``deep'' ideas about types in Scala, which even to |
|
1184 |
me as seasoned functional programmer are puzzling. Whilst |
|
1185 |
implicits are great, they can also be a source of great |
|
1186 |
headaches, for example consider the code: |
|
1187 |
||
1188 |
\begin{lstlisting}[numbers=none] |
|
1189 |
scala> List (1, 2, 3) contains "your mom" |
|
1190 |
res1: Boolean = false |
|
1191 |
\end{lstlisting} |
|
1192 |
||
1193 |
\noindent Rather than returning \code{false}, this code should |
|
1194 |
throw a typing-error. There are also many limitations Scala |
|
1195 |
inherited from the JVM that can be really annoying. For |
|
1196 |
example a fixed stack size. One can work around this |
|
1197 |
particular limitation, but why does one have to? |
|
1198 |
More such `puzzles' can be found at |
|
1199 |
||
1200 |
\begin{center} |
|
1201 |
\url{http://scalapuzzlers.com} and |
|
1202 |
\url{http://latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/} |
|
1203 |
\end{center} |
|
191 | 1204 |
|
1205 |
Even if Scala has been a success in several high-profile companies, |
|
1206 |
there is also a company (Yammer) that first used Scala in their |
|
1207 |
production code, but then moved away from it. Allegedly they did not |
|
1208 |
like the steep learning curve of Scala and also that new versions of |
|
1209 |
Scala often introduced incompatibilities in old code. Also the Java |
|
197 | 1210 |
language is lately developing at lightening speed (in comparison to the past) |
1211 |
taking on many |
|
191 | 1212 |
features of Scala and other languages, and it seems even it introduces |
1213 |
new features on its own. |
|
123 | 1214 |
|
152 | 1215 |
%So all in all, Scala might not be a great teaching language, |
1216 |
%but I hope this is mitigated by the fact that I never require |
|
1217 |
%you to write any Scala code. You only need to be able to read |
|
1218 |
%it. In the coursework you can use any programming language you |
|
1219 |
%like. If you want to use Scala for this, then be my guest; if |
|
1220 |
%you do not want, stick with the language you are most familiar |
|
1221 |
%with. |
|
123 | 1222 |
|
1223 |
||
191 | 1224 |
\subsection*{Conclusion} |
1225 |
||
198 | 1226 |
I hope you liked the short journey through the Scala language---but remember we |
197 | 1227 |
like you to take on board the functional programming point of view, |
198 | 1228 |
rather than just learning another language. There is an interesting |
1229 |
blog article about Scala by a convert: |
|
1230 |
||
1231 |
\begin{center} |
|
1232 |
\url{https://www.skedulo.com/tech-blog/technology-scala-programming/} |
|
1233 |
\end{center} |
|
1234 |
||
1235 |
\noindent |
|
1236 |
He makes pretty much the same arguments about functional programming and |
|
1237 |
immutability (one section is teasingly called \textit{``Where Did all |
|
1238 |
the Bugs Go?''}). If you happen to moan about all the idiotic features |
|
1239 |
of Scala, well, I guess this is part of the package according to this |
|
1240 |
quote:\bigskip |
|
197 | 1241 |
|
1242 |
%\begin{itemize} |
|
1243 |
%\item no exceptions....there two kinds, one ``global'' exceptions, like |
|
1244 |
%out of memory (not much can be done about this by the ``individual'' |
|
1245 |
%programmer); and ``local one'' open a file that might not exists - in |
|
1246 |
%the latter you do not want to use exceptions, but Options |
|
1247 |
%\end{itemize} |
|
123 | 1248 |
|
182 | 1249 |
\begin{flushright}\it |
1250 |
There are only two kinds of languages: the ones people complain |
|
1251 |
about\\ and the ones nobody uses.\smallskip\\ |
|
1252 |
\mbox{}\hfill\small{}---Bjarne Stroustrup (the inventor of C++) |
|
1253 |
\end{flushright} |
|
1254 |
||
123 | 1255 |
\end{document} |
1256 |
||
1257 |
%%% Local Variables: |
|
1258 |
%%% mode: latex |
|
1259 |
%%% TeX-master: t |
|
1260 |
%%% End: |