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