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