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