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