123
|
1 |
\documentclass{article}
|
|
2 |
\usepackage{../style}
|
|
3 |
\usepackage{../langs}
|
|
4 |
\usepackage{marvosym}
|
|
5 |
|
|
6 |
%cheat sheet
|
|
7 |
%http://worldline.github.io/scala-cheatsheet/
|
|
8 |
|
170
|
9 |
% case class, apply, unappy
|
|
10 |
% see https://medium.com/@thejasbabu/scala-pattern-matching-9c9e73ba9a8a
|
|
11 |
|
123
|
12 |
\begin{document}
|
|
13 |
|
125
|
14 |
\section*{A Crash-Course in Scala}
|
123
|
15 |
|
178
|
16 |
\mbox{}\hfill\textit{``Scala --- Slowly Compiled Academic LAnguage''}\\
|
|
17 |
\mbox{}\hfill\textit{ --- joke on Twitter}\bigskip
|
|
18 |
|
|
19 |
\noindent
|
170
|
20 |
Scala is a programming language that combines functional and
|
|
21 |
object-oriented programming-styles. It has received quite a bit of
|
|
22 |
attention in the last five or so years. One reason for this attention
|
|
23 |
is that, like the Java programming language, Scala compiles to the
|
|
24 |
Java Virtual Machine (JVM) and therefore Scala programs can run under
|
|
25 |
MacOSX, Linux and Windows.\footnote{There are also experimental
|
|
26 |
backends for Android and JavaScript; and also work is under way to
|
|
27 |
have a native compiler, see
|
|
28 |
\url{https://github.com/scala-native/scala-native}.} Unlike Java,
|
|
29 |
however, Scala often allows programmers to write very concise and
|
|
30 |
elegant code. Some therefore say: ``Scala is the better
|
|
31 |
Java''.\footnote{\url{https://www.slideshare.net/maximnovak/joy-of-scala}}
|
|
32 |
Also a number of companies (the Guardian, Twitter, Coursera,
|
|
33 |
FourSquare, LinkedIn to name a few) either use Scala exclusively in
|
|
34 |
production code, or at least to some substantial degree. Scala seems
|
|
35 |
also to be useful in job-interviews (in Data Science) according to
|
|
36 |
this anecdotal report
|
|
37 |
|
|
38 |
\begin{quote}\small
|
|
39 |
\url{https://techcrunch.com/2016/06/14/scala-is-the-new-golden-child/}
|
|
40 |
\end{quote}
|
|
41 |
|
|
42 |
\noindent
|
|
43 |
The official Scala compiler can be downloaded from
|
|
44 |
|
|
45 |
\begin{quote}
|
|
46 |
\url{http://www.scala-lang.org}
|
|
47 |
\end{quote}
|
|
48 |
|
|
49 |
\noindent
|
|
50 |
A ready-made bundle with the Eclipse IDE is at
|
|
51 |
|
|
52 |
\begin{quote}
|
|
53 |
\url{http://scala-ide.org/download/sdk.html}
|
|
54 |
\end{quote}
|
|
55 |
|
|
56 |
\noindent
|
|
57 |
When developing Scala programs, I personally prefer to use Emacs
|
|
58 |
or Sublime as my environment, since they provide an easy access
|
|
59 |
to the Scala REPL (see below). But it is also possible to work
|
|
60 |
completely on the command line and also with heavy-duty IDEs
|
|
61 |
like Eclipse of IntelliJ. There is even an online editor and
|
|
62 |
environment for developing Scala programs called ScalaFiddle
|
|
63 |
|
|
64 |
\begin{quote}
|
|
65 |
\url{https://scalafiddle.io}
|
|
66 |
\end{quote}
|
|
67 |
|
|
68 |
|
|
69 |
|
|
70 |
|
123
|
71 |
\subsection*{The Very Basics}
|
|
72 |
|
|
73 |
One advantage of Scala over Java is that it includes an interpreter (a
|
|
74 |
REPL, or
|
|
75 |
\underline{R}ead-\underline{E}val-\underline{P}rint-\underline{L}oop)
|
|
76 |
with which you can run and test small code-snippets without the need
|
|
77 |
of a compiler. This helps a lot with interactively developing
|
170
|
78 |
programs. This is really the preferred way of writing small Scala
|
123
|
79 |
programs. Once you installed Scala, you can start the interpreter by
|
|
80 |
typing on the command line:
|
|
81 |
|
|
82 |
\begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
|
|
83 |
$ scala
|
|
84 |
Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 9).
|
|
85 |
Type in expressions for evaluation. Or try :help.
|
|
86 |
|
|
87 |
scala>
|
|
88 |
\end{lstlisting}%$
|
|
89 |
|
|
90 |
\noindent The precise response may vary depending
|
|
91 |
on the version and platform where you installed Scala. At the Scala
|
|
92 |
prompt you can type things like \code{2 + 3}\;\keys{Ret} and
|
|
93 |
the output will be
|
|
94 |
|
|
95 |
\begin{lstlisting}[numbers=none]
|
|
96 |
scala> 2 + 3
|
|
97 |
res0: Int = 5
|
|
98 |
\end{lstlisting}
|
|
99 |
|
124
|
100 |
\noindent indicating that the result of the addition is of type
|
|
101 |
\code{Int} and the actual result is 5; \code{res0} is a name that
|
125
|
102 |
Scala gives automatically to the result. You can reuse this name later
|
124
|
103 |
on. Another classic example you can try out is
|
123
|
104 |
|
|
105 |
\begin{lstlisting}[numbers=none]
|
|
106 |
scala> print("hello world")
|
|
107 |
hello world
|
|
108 |
\end{lstlisting}
|
|
109 |
|
|
110 |
\noindent Note that in this case there is no result. The
|
|
111 |
reason is that \code{print} does not actually produce a result
|
124
|
112 |
(there is no \code{resX} and no type), rather it is a
|
123
|
113 |
function that causes the \emph{side-effect} of printing out a
|
|
114 |
string. Once you are more familiar with the functional
|
|
115 |
programming-style, you will know what the difference is
|
|
116 |
between a function that returns a result, like addition, and a
|
|
117 |
function that causes a side-effect, like \code{print}. We
|
|
118 |
shall come back to this point later, but if you are curious
|
|
119 |
now, the latter kind of functions always has \code{Unit} as
|
124
|
120 |
return type. It is just not printed.
|
123
|
121 |
|
|
122 |
You can try more examples with the Scala interpreter, but try
|
|
123 |
first to guess what the result is (not all answers by Scala are obvious):
|
|
124 |
|
|
125 |
\begin{lstlisting}[numbers=none]
|
|
126 |
scala> 2 + 2
|
|
127 |
scala> 1 / 2
|
|
128 |
scala> 1.0 / 2
|
|
129 |
scala> 1 / 2.0
|
|
130 |
scala> 1 / 0
|
|
131 |
scala> 1.0 / 0.0
|
|
132 |
scala> true == false
|
|
133 |
scala> true && false
|
|
134 |
scala> 1 > 1.0
|
|
135 |
scala> "12345".length
|
|
136 |
\end{lstlisting}
|
|
137 |
|
124
|
138 |
\subsection*{Stand-Alone Scala Apps}
|
123
|
139 |
|
|
140 |
If you want to write a stand-alone app in Scala, you can
|
|
141 |
implement an object that is an instance of \code{App}, say
|
|
142 |
|
|
143 |
\begin{lstlisting}[numbers=none]
|
|
144 |
object Hello extends App {
|
|
145 |
println("hello world")
|
|
146 |
}
|
|
147 |
\end{lstlisting}
|
|
148 |
|
124
|
149 |
\noindent save it in a file, for example {\tt hello-world.scala}, and
|
123
|
150 |
then run the compiler and runtime environment:
|
|
151 |
|
|
152 |
\begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
|
|
153 |
$ scalac hello-world.scala
|
|
154 |
$ scala Hello
|
|
155 |
hello world
|
|
156 |
\end{lstlisting}
|
|
157 |
|
124
|
158 |
\noindent
|
123
|
159 |
Like Java, Scala targets the JVM and consequently
|
|
160 |
Scala programs can also be executed by the bog-standard Java
|
|
161 |
Runtime. This only requires the inclusion of {\tt
|
|
162 |
scala-library.jar}, which on my computer can be done as
|
|
163 |
follows:
|
|
164 |
|
|
165 |
\begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
|
|
166 |
$ scalac hello-world.scala
|
|
167 |
$ java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
|
|
168 |
hello world
|
|
169 |
\end{lstlisting}
|
|
170 |
|
|
171 |
\noindent You might need to adapt the path to where you have
|
|
172 |
installed Scala.
|
|
173 |
|
|
174 |
\subsection*{Values}
|
|
175 |
|
124
|
176 |
In the lectures I will try to avoid as much as possible the term
|
|
177 |
\emph{variables} familiar from other programming languages. The reason
|
|
178 |
is that Scala has \emph{values}, which can be seen as abbreviations of
|
|
179 |
larger expressions. For example
|
123
|
180 |
|
|
181 |
\begin{lstlisting}[numbers=none]
|
|
182 |
scala> val x = 42
|
|
183 |
x: Int = 42
|
|
184 |
|
|
185 |
scala> val y = 3 + 4
|
|
186 |
y: Int = 7
|
|
187 |
|
|
188 |
scala> val z = x / y
|
|
189 |
z: Int = 6
|
|
190 |
\end{lstlisting}
|
|
191 |
|
|
192 |
\noindent
|
|
193 |
Why the kerfuffle about values? Well, values are \emph{immutable}. You cannot
|
124
|
194 |
change their value after you defined them. If you try to reassign
|
|
195 |
\code{z} above, Scala will yell at you:
|
123
|
196 |
|
|
197 |
\begin{lstlisting}[numbers=none]
|
|
198 |
scala> z = 9
|
|
199 |
error: reassignment to val
|
|
200 |
z = 9
|
|
201 |
^
|
|
202 |
\end{lstlisting}
|
|
203 |
|
|
204 |
\noindent
|
|
205 |
So it would be a bit absurd to call values as variables...you cannot
|
|
206 |
change them. You might think you can re-assign them like
|
|
207 |
|
|
208 |
\begin{lstlisting}[numbers=none]
|
|
209 |
scala> val x = 42
|
|
210 |
scala> val z = x / 7
|
|
211 |
scala> val x = 70
|
|
212 |
scala> println(z)
|
|
213 |
\end{lstlisting}
|
|
214 |
|
124
|
215 |
\noindent but try to guess what Scala will print out
|
123
|
216 |
for \code{z}? Will it be \code{6} or \code{10}? A final word about
|
|
217 |
values: Try to stick to the convention that names of values should be
|
|
218 |
lower case, like \code{x}, \code{y}, \code{foo41} and so on.
|
|
219 |
|
|
220 |
|
|
221 |
\subsection*{Function Definitions}
|
|
222 |
|
124
|
223 |
We do functional programming. So defining functions will be our main occupation.
|
|
224 |
A function \code{f} taking a single argument of type \code{Int} can be defined in Scala
|
123
|
225 |
as follows:
|
|
226 |
|
|
227 |
\begin{lstlisting}[numbers=none]
|
|
228 |
def f(x: Int) : String = EXPR
|
|
229 |
\end{lstlisting}
|
|
230 |
|
|
231 |
\noindent
|
124
|
232 |
This function returns the value resulting from evaluating the expression
|
123
|
233 |
\code{EXPR} (whatever is substituted for this). The result will be
|
124
|
234 |
of type \code{String}. It is a good habbit to include this information
|
|
235 |
about the return type always. Simple examples of Scala functions are:
|
123
|
236 |
|
|
237 |
\begin{lstlisting}[numbers=none]
|
|
238 |
def incr(x: Int) : Int = x + 1
|
|
239 |
def double(x: Int) : Int = x + x
|
|
240 |
def square(x: Int) : Int = x * x
|
|
241 |
\end{lstlisting}
|
|
242 |
|
|
243 |
\noindent
|
|
244 |
The general scheme for a function is
|
|
245 |
|
|
246 |
\begin{lstlisting}[numbers=none]
|
|
247 |
def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
|
|
248 |
BODY
|
|
249 |
}
|
|
250 |
\end{lstlisting}
|
|
251 |
|
|
252 |
\noindent
|
|
253 |
where each argument requires its type and the result type of the
|
124
|
254 |
function, \code{rty}, should be given. If the body of the function is
|
|
255 |
more complex, then it can be enclosed in braces, like above. If it it
|
|
256 |
is just a simple expression, like \code{x + 1}, you can omit the
|
|
257 |
braces. Very often functions are recursive (call themselves) like
|
|
258 |
the venerable factorial function.
|
123
|
259 |
|
|
260 |
\begin{lstlisting}[numbers=none]
|
|
261 |
def fact(n: Int): Int =
|
|
262 |
if (n == 0) 1 else n * fact(n - 1)
|
|
263 |
\end{lstlisting}
|
|
264 |
|
|
265 |
\subsection*{Loops, or better the Absence thereof}
|
|
266 |
|
|
267 |
Coming from Java or C++, you might be surprised that Scala does
|
|
268 |
not really have loops. It has instead, what is in functional
|
|
269 |
programming called, \emph{maps}. To illustrate how they work,
|
|
270 |
let us assume you have a list of numbers from 1 to 8 and want to
|
|
271 |
build the list of squares. The list of numbers from 1 to 8
|
|
272 |
can be constructed in Scala as follows:
|
|
273 |
|
|
274 |
\begin{lstlisting}[numbers=none]
|
|
275 |
scala> (1 to 8).toList
|
|
276 |
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)
|
|
277 |
\end{lstlisting}
|
|
278 |
|
|
279 |
\noindent Generating from this list, the list of squares in a
|
|
280 |
programming language such as Java, you would assume the list
|
|
281 |
is given as a kind of array. You would then iterate, or loop,
|
|
282 |
an index over this array and replace each entry in the array
|
|
283 |
by the square. Right? In Scala, and in other functional
|
|
284 |
programming languages, you use maps to achieve the same.
|
|
285 |
|
|
286 |
A map essentially takes a function that describes how each
|
|
287 |
element is transformed (for example squared) and a list over
|
|
288 |
which this function should work. There are two forms to
|
|
289 |
express such maps in Scala. The first way is called a
|
|
290 |
\emph{for-comprehension}. Squaring the numbers from 1 to 8
|
|
291 |
would look as follows:
|
|
292 |
|
|
293 |
\begin{lstlisting}[numbers=none]
|
|
294 |
scala> for (n <- (1 to 8).toList) yield n * n
|
|
295 |
res2: List[Int] = List(1, 4, 9, 16, 25, 36, 49, 64)
|
|
296 |
\end{lstlisting}
|
|
297 |
|
|
298 |
\noindent The important keywords are \code{for} and
|
|
299 |
\code{yield}. This for-comprehension roughly states that from
|
|
300 |
the list of numbers we draw \code{n}s and compute the result
|
|
301 |
of \code{n * n}. As you can see, we specified the list where
|
|
302 |
each \code{n} comes from, namely \code{(1 to 8).toList}, and
|
|
303 |
how each element needs to be transformed. This can also be
|
|
304 |
expressed in a second way in Scala by using directly
|
|
305 |
\code{map}s as follows:
|
|
306 |
|
|
307 |
\begin{lstlisting}[numbers=none]
|
|
308 |
scala> (1 to 8).toList.map(n => n * n)
|
|
309 |
res3 = List(1, 4, 9, 16, 25, 36, 49, 64)
|
|
310 |
\end{lstlisting}
|
|
311 |
|
|
312 |
\noindent In this way, the expression \code{n => n * n} stands
|
|
313 |
for the function that calculates the square (this is how the
|
|
314 |
\code{n}s are transformed). This expression for functions
|
|
315 |
might remind you of your lessons about the lambda-calculus
|
|
316 |
where this would have been written as $\lambda n.\,n * n$. It
|
|
317 |
might not be obvious, but for-comprehensions are just
|
|
318 |
syntactic sugar: when compiling, Scala translates
|
|
319 |
for-comprehensions into equivalent maps. This even works
|
|
320 |
when for-comprehensions get more complicated (see below).
|
|
321 |
|
|
322 |
The very charming feature of Scala is that such maps or
|
|
323 |
for-comprehensions can be written for any kind of data
|
|
324 |
collection, such as lists, sets, vectors, options and so on.
|
|
325 |
For example if we instead compute the reminders modulo 3 of
|
|
326 |
this list, we can write
|
|
327 |
|
|
328 |
\begin{lstlisting}[numbers=none]
|
|
329 |
scala> (1 to 8).toList.map(n => n % 3)
|
|
330 |
res4 = List(1, 2, 0, 1, 2, 0, 1, 2)
|
|
331 |
\end{lstlisting}
|
|
332 |
|
|
333 |
\noindent If we, however, transform the numbers 1 to 8 not
|
|
334 |
into a list, but into a set, and then compute the reminders
|
|
335 |
modulo 3 we obtain
|
|
336 |
|
|
337 |
\begin{lstlisting}[numbers=none]
|
|
338 |
scala> (1 to 8).toSet[Int].map(n => n % 3)
|
|
339 |
res5 = Set(2, 1, 0)
|
|
340 |
\end{lstlisting}
|
|
341 |
|
|
342 |
\noindent This is the correct result for sets, as there are
|
|
343 |
only three equivalence classes of integers modulo 3. Note that
|
|
344 |
in this example we need to ``help'' Scala to transform the
|
|
345 |
numbers into a set of integers by explicitly annotating the
|
|
346 |
type \code{Int}. Since maps and for-comprehensions are
|
|
347 |
just syntactic variants of each other, the latter can also be
|
|
348 |
written as
|
|
349 |
|
|
350 |
\begin{lstlisting}[numbers=none]
|
|
351 |
scala> for (n <- (1 to 8).toSet[Int]) yield n % 3
|
|
352 |
res5 = Set(2, 1, 0)
|
|
353 |
\end{lstlisting}
|
|
354 |
|
|
355 |
For-comprehensions can also be nested and the selection of
|
|
356 |
elements can be guarded. For example if we want to pair up
|
|
357 |
the numbers 1 to 4 with the letters a to c, we can write
|
|
358 |
|
|
359 |
\begin{lstlisting}[numbers=none]
|
|
360 |
scala> for (n <- (1 to 4).toList;
|
|
361 |
m <- ('a' to 'c').toList) yield (n, m)
|
|
362 |
res6 = List((1,a), (1,b), (1,c), (2,a), (2,b), (2,c),
|
|
363 |
(3,a), (3,b), (3,c), (4,a), (4,b), (4,c))
|
|
364 |
\end{lstlisting}
|
|
365 |
|
|
366 |
\noindent
|
|
367 |
Or if we want to find all pairs of numbers between 1 and 3
|
|
368 |
where the sum is an even number, we can write
|
|
369 |
|
|
370 |
\begin{lstlisting}[numbers=none]
|
|
371 |
scala> for (n <- (1 to 3).toList;
|
|
372 |
m <- (1 to 3).toList;
|
|
373 |
if (n + m) % 2 == 0) yield (n, m)
|
|
374 |
res7 = List((1,1), (1,3), (2,2), (3,1), (3,3))
|
|
375 |
\end{lstlisting}
|
|
376 |
|
|
377 |
\noindent The \code{if}-condition in the for-comprehension
|
|
378 |
filters out all pairs where the sum is not even.
|
|
379 |
|
|
380 |
While hopefully this all looks reasonable, there is one
|
|
381 |
complication: In the examples above we always wanted to
|
|
382 |
transform one list into another list (e.g.~list of squares),
|
|
383 |
or one set into another set (set of numbers into set of
|
|
384 |
reminders modulo 3). What happens if we just want to print out
|
|
385 |
a list of integers? Then actually the for-comprehension
|
|
386 |
needs to be modified. The reason is that \code{print}, you
|
|
387 |
guessed it, does not produce any result, but only produces
|
|
388 |
what is in the functional-programming-lingo called a
|
|
389 |
side-effect. Printing out the list of numbers from 1 to 5
|
|
390 |
would look as follows
|
|
391 |
|
|
392 |
\begin{lstlisting}[numbers=none]
|
|
393 |
scala> for (n <- (1 to 5).toList) print(n)
|
|
394 |
12345
|
|
395 |
\end{lstlisting}
|
|
396 |
|
|
397 |
\noindent
|
|
398 |
where you need to omit the keyword \code{yield}. You can
|
|
399 |
also do more elaborate calculations such as
|
|
400 |
|
|
401 |
\begin{lstlisting}[numbers=none]
|
|
402 |
scala> for (n <- (1 to 5).toList) {
|
|
403 |
val square_n = n * n
|
|
404 |
println(s"$n * $n = $square_n")
|
|
405 |
}
|
|
406 |
1 * 1 = 1
|
|
407 |
2 * 2 = 4
|
|
408 |
3 * 3 = 9
|
|
409 |
4 * 4 = 16
|
|
410 |
5 * 5 = 25
|
|
411 |
\end{lstlisting}%$
|
|
412 |
|
|
413 |
\noindent In this code I use a variable assignment (\code{val
|
|
414 |
square_n = ...} ) and also what is called in Scala a
|
|
415 |
\emph{string interpolation}, written \code{s"..."}. The latter
|
|
416 |
is for printing out an equation. It allows me to refer to the
|
|
417 |
integer values \code{n} and \code{square\_n} inside a string.
|
|
418 |
This is very convenient for printing out ``things''.
|
|
419 |
|
|
420 |
The corresponding map construction for functions with
|
|
421 |
side-effects is in Scala called \code{foreach}. So you
|
|
422 |
could also write
|
|
423 |
|
|
424 |
|
|
425 |
\begin{lstlisting}[numbers=none]
|
|
426 |
scala> (1 to 5).toList.foreach(n => print(n))
|
|
427 |
12345
|
|
428 |
\end{lstlisting}
|
|
429 |
|
|
430 |
|
|
431 |
\noindent or even just
|
|
432 |
|
|
433 |
\begin{lstlisting}[numbers=none]
|
|
434 |
scala> (1 to 5).toList.foreach(print)
|
|
435 |
12345
|
|
436 |
\end{lstlisting}
|
|
437 |
|
|
438 |
\noindent Again I hope this reminds you a bit of your
|
|
439 |
lambda-calculus lessons, where an explanation is given why
|
|
440 |
both forms produce the same result.
|
|
441 |
|
|
442 |
|
|
443 |
If you want to find out more about maps and functions with
|
|
444 |
side-effects, you can ponder about the response Scala gives if
|
|
445 |
you replace \code{foreach} by \code{map} in the expression
|
|
446 |
above. Scala will still allow \code{map} with side-effect
|
|
447 |
functions, but then reacts with a slightly interesting result.
|
|
448 |
|
|
449 |
\subsection*{Types}
|
|
450 |
|
|
451 |
In most functional programming languages, types play an
|
|
452 |
important role. Scala is such a language. You have already
|
|
453 |
seen built-in types, like \code{Int}, \code{Boolean},
|
|
454 |
\code{String} and \code{BigInt}, but also user-defined ones,
|
|
455 |
like \code{Rexp}. Unfortunately, types can be a thorny
|
|
456 |
subject, especially in Scala. For example, why do we need to
|
|
457 |
give the type to \code{toSet[Int]}, but not to \code{toList}?
|
|
458 |
The reason is the power of Scala, which sometimes means it
|
|
459 |
cannot infer all necessary typing information. At the
|
|
460 |
beginning while getting familiar with Scala, I recommend a
|
|
461 |
``play-it-by-ear-approach'' to types. Fully understanding
|
|
462 |
type-systems, especially complicated ones like in Scala, can
|
|
463 |
take a module on their own.\footnote{Still, such a study can
|
|
464 |
be a rewarding training: If you are in the business of
|
|
465 |
designing new programming languages, you will not be able to
|
|
466 |
turn a blind eye to types. They essentially help programmers
|
|
467 |
to avoid common programming errors and help with maintaining
|
|
468 |
code.}
|
|
469 |
|
|
470 |
In Scala, types are needed whenever you define an inductive
|
|
471 |
datatype and also whenever you define functions (their
|
|
472 |
arguments and their results need a type). Base types are types
|
|
473 |
that do not take any (type)arguments, for example \code{Int}
|
|
474 |
and \code{String}. Compound types take one or more arguments,
|
|
475 |
which as seen earlier need to be given in angle-brackets, for
|
|
476 |
example \code{List[Int]} or \code{Set[List[String]]} or
|
|
477 |
\code{Map[Int, Int]}.
|
|
478 |
|
|
479 |
There are a few special type-constructors that fall outside
|
|
480 |
this pattern. One is for tuples, where the type is written
|
|
481 |
with parentheses. For example
|
|
482 |
|
|
483 |
\begin{lstlisting}[ numbers=none]
|
|
484 |
(Int, Int, String)
|
|
485 |
\end{lstlisting}
|
|
486 |
|
|
487 |
\noindent is for a triple (a tuple with three components---two
|
|
488 |
integers and a string). Tuples are helpful if you want to
|
|
489 |
define functions with multiple results, say the function
|
|
490 |
returning the quotient and reminder of two numbers. For this
|
|
491 |
you might define:
|
|
492 |
|
|
493 |
|
|
494 |
\begin{lstlisting}[ numbers=none]
|
|
495 |
def quo_rem(m: Int, n: Int) : (Int, Int) = (m / n, m % n)
|
|
496 |
\end{lstlisting}
|
|
497 |
|
|
498 |
|
|
499 |
\noindent Since this function returns a pair of integers, its
|
|
500 |
return type needs to be of type \code{(Int, Int)}.
|
|
501 |
Incidentally, this is also the input type of this function.
|
|
502 |
Notice this function takes \emph{two} arguments, namely
|
|
503 |
\code{m} and \code{n}, both of which are integers. They are
|
|
504 |
``packaged'' in a pair. Consequently the complete type of
|
|
505 |
\code{quo_rem} is
|
|
506 |
|
|
507 |
\begin{lstlisting}[ numbers=none]
|
|
508 |
(Int, Int) => (Int, Int)
|
|
509 |
\end{lstlisting}
|
|
510 |
|
|
511 |
Another special type-constructor is for functions, written as
|
|
512 |
the arrow \code{=>}. For example, the type \code{Int =>
|
|
513 |
String} is for a function that takes an integer as input
|
|
514 |
argument and produces a string as result. A function of this
|
|
515 |
type is for instance
|
|
516 |
|
|
517 |
\begin{lstlisting}[numbers=none]
|
|
518 |
def mk_string(n: Int) : String = n match {
|
|
519 |
case 0 => "zero"
|
|
520 |
case 1 => "one"
|
|
521 |
case 2 => "two"
|
|
522 |
case _ => "many"
|
|
523 |
}
|
|
524 |
\end{lstlisting}
|
|
525 |
|
|
526 |
\noindent It takes an integer as input argument and returns a
|
|
527 |
string. Unlike other functional programming languages, there
|
|
528 |
is in Scala no easy way to find out the types of existing
|
|
529 |
functions, except by looking into the documentation
|
|
530 |
|
|
531 |
\begin{quote}
|
|
532 |
\url{http://www.scala-lang.org/api/current/}
|
|
533 |
\end{quote}
|
|
534 |
|
|
535 |
The function arrow can also be iterated, as in
|
|
536 |
\code{Int => String => Boolean}. This is the type for a function
|
|
537 |
taking an integer as first argument and a string as second,
|
|
538 |
and the result of the function is a boolean. Though silly, a
|
|
539 |
function of this type would be
|
|
540 |
|
|
541 |
|
|
542 |
\begin{lstlisting}[numbers=none]
|
|
543 |
def chk_string(n: Int)(s: String) : Boolean =
|
|
544 |
mk_string(n) == s
|
|
545 |
\end{lstlisting}
|
|
546 |
|
|
547 |
|
|
548 |
\noindent which checks whether the integer \code{n}
|
|
549 |
corresponds to the name \code{s} given by the function
|
|
550 |
\code{mk\_string}. Notice the unusual way of specifying the
|
|
551 |
arguments of this function: the arguments are given one after
|
|
552 |
the other, instead of being in a pair (what would be the type
|
|
553 |
of this function then?). This way of specifying the arguments
|
|
554 |
can be useful, for example in situations like this
|
|
555 |
|
|
556 |
\begin{lstlisting}[numbers=none]
|
|
557 |
scala> List("one", "two", "three", "many").map(chk_string(2))
|
|
558 |
res4 = List(false, true, false, false)
|
|
559 |
|
|
560 |
scala> List("one", "two", "three", "many").map(chk_string(3))
|
|
561 |
res5 = List(false, false, false, true)
|
|
562 |
\end{lstlisting}
|
|
563 |
|
|
564 |
\noindent In each case we can give to \code{map} a specialised
|
|
565 |
version of \code{chk_string}---once specialised to 2 and once
|
|
566 |
to 3. This kind of ``specialising'' a function is called
|
|
567 |
\emph{partial application}---we have not yet given to this
|
|
568 |
function all arguments it needs, but only some of them.
|
|
569 |
|
|
570 |
Coming back to the type \code{Int => String => Boolean}. The
|
|
571 |
rule about such function types is that the right-most type
|
|
572 |
specifies what the function returns (a boolean in this case).
|
|
573 |
The types before that specify how many arguments the function
|
|
574 |
expects and what their type is (in this case two arguments,
|
|
575 |
one of type \code{Int} and another of type \code{String}).
|
|
576 |
Given this rule, what kind of function has type
|
|
577 |
\mbox{\code{(Int => String) => Boolean}}? Well, it returns a
|
|
578 |
boolean. More interestingly, though, it only takes a single
|
|
579 |
argument (because of the parentheses). The single argument
|
|
580 |
happens to be another function (taking an integer as input and
|
|
581 |
returning a string). Remember that \code{mk_string} is just
|
|
582 |
such a function. So how can we use it? For this define
|
|
583 |
the somewhat silly function \code{apply_3}:
|
|
584 |
|
|
585 |
\begin{lstlisting}[numbers=none]
|
|
586 |
def apply_3(f: Int => String): Bool = f(3) == "many"
|
|
587 |
|
|
588 |
scala> apply_3(mk_string)
|
|
589 |
res6 = true
|
|
590 |
\end{lstlisting}
|
|
591 |
|
|
592 |
You might ask: Apart from silly functions like above, what is
|
|
593 |
the point of having functions as input arguments to other
|
|
594 |
functions? In Java there is indeed no need of this kind of
|
|
595 |
feature: at least in the past it did not allow such
|
|
596 |
constructions. I think, the point of Java 8 is to lift this
|
|
597 |
restriction. But in all functional programming languages,
|
|
598 |
including Scala, it is really essential to allow functions as
|
|
599 |
input argument. Above you already seen \code{map} and
|
|
600 |
\code{foreach} which need this. Consider the functions
|
|
601 |
\code{print} and \code{println}, which both print out strings,
|
|
602 |
but the latter adds a line break. You can call \code{foreach}
|
|
603 |
with either of them and thus changing how, for example, five
|
|
604 |
numbers are printed.
|
|
605 |
|
|
606 |
|
|
607 |
\begin{lstlisting}[numbers=none]
|
|
608 |
scala> (1 to 5).toList.foreach(print)
|
|
609 |
12345
|
|
610 |
scala> (1 to 5).toList.foreach(println)
|
|
611 |
1
|
|
612 |
2
|
|
613 |
3
|
|
614 |
4
|
|
615 |
5
|
|
616 |
\end{lstlisting}
|
|
617 |
|
|
618 |
|
|
619 |
\noindent This is actually one of the main design principles
|
|
620 |
in functional programming. You have generic functions like
|
|
621 |
\code{map} and \code{foreach} that can traverse data containers,
|
|
622 |
like lists or sets. They then take a function to specify what
|
|
623 |
should be done with each element during the traversal. This
|
|
624 |
requires that the generic traversal functions can cope with
|
|
625 |
any kind of function (not just functions that, for example,
|
|
626 |
take as input an integer and produce a string like above).
|
|
627 |
This means we cannot fix the type of the generic traversal
|
|
628 |
functions, but have to keep them
|
|
629 |
\emph{polymorphic}.\footnote{Another interestic topic about
|
|
630 |
types, but we omit it here for the sake of brevity.}
|
|
631 |
|
|
632 |
There is one more type constructor that is rather special. It
|
|
633 |
is called \code{Unit}. Recall that \code{Boolean} has two
|
|
634 |
values, namely \code{true} and \code{false}. This can be used,
|
|
635 |
for example, to test something and decide whether the test
|
|
636 |
succeeds or not. In contrast the type \code{Unit} has only a
|
|
637 |
single value, written \code{()}. This seems like a completely
|
|
638 |
useless type and return value for a function, but is actually
|
|
639 |
quite useful. It indicates when the function does not return
|
|
640 |
any result. The purpose of these functions is to cause
|
|
641 |
something being written on the screen or written into a file,
|
|
642 |
for example. This is what is called they cause some effect on
|
|
643 |
the side, namely a new content displayed on the screen or some
|
|
644 |
new data in a file. Scala uses the \code{Unit} type to indicate
|
|
645 |
that a function does not have a result, but potentially causes
|
|
646 |
some side-effect. Typical examples are the printing functions,
|
|
647 |
like \code{print}.
|
|
648 |
|
|
649 |
|
143
|
650 |
% \subsection*{Cool Stuff}
|
123
|
651 |
|
143
|
652 |
% The first wow-moment I had with Scala was when I came across
|
|
653 |
% the following code-snippet for reading a web-page.
|
123
|
654 |
|
|
655 |
|
143
|
656 |
% \begin{lstlisting}[ numbers=none]
|
|
657 |
% import io.Source
|
|
658 |
% val url = """http://www.inf.kcl.ac.uk/staff/urbanc/"""
|
|
659 |
% Source.fromURL(url)("ISO-8859-1").take(10000).mkString
|
|
660 |
% \end{lstlisting}
|
123
|
661 |
|
|
662 |
|
143
|
663 |
% \noindent These three lines return a string containing the
|
|
664 |
% HTML-code of my webpage. It actually already does something
|
|
665 |
% more sophisticated, namely only returns the first 10000
|
|
666 |
% characters of a webpage in case it is too large. Why is that
|
|
667 |
% code-snippet of any interest? Well, try implementing
|
|
668 |
% reading-from-a-webpage in Java. I also like the possibility of
|
|
669 |
% triple-quoting strings, which I have only seen in Scala so
|
|
670 |
% far. The idea behind this is that in such a string all
|
|
671 |
% characters are interpreted literally---there are no escaped
|
|
672 |
% characters, like \verb|\n| for newlines.
|
123
|
673 |
|
143
|
674 |
% My second wow-moment I had with a feature of Scala that other
|
|
675 |
% functional programming languages do not have. This feature is
|
|
676 |
% about implicit type conversions. If you have regular
|
|
677 |
% expressions and want to use them for language processing you
|
|
678 |
% often want to recognise keywords in a language, for example
|
|
679 |
% \code{for},{} \code{if},{} \code{yield} and so on. But the
|
|
680 |
% basic regular expression \code{CHAR} can only recognise a
|
|
681 |
% single character. In order to recognise a whole string, like
|
|
682 |
% \code{for}, you have to put many of those together using
|
|
683 |
% \code{SEQ}:
|
123
|
684 |
|
|
685 |
|
143
|
686 |
% \begin{lstlisting}[numbers=none]
|
|
687 |
% SEQ(CHAR('f'), SEQ(CHAR('o'), CHAR('r')))
|
|
688 |
% \end{lstlisting}
|
123
|
689 |
|
143
|
690 |
% \noindent This gets quickly unreadable when the strings and
|
|
691 |
% regular expressions get more complicated. In other functional
|
|
692 |
% programming languages, you can explicitly write a conversion
|
|
693 |
% function that takes a string, say \dq{\pcode{for}}, and
|
|
694 |
% generates the regular expression above. But then your code is
|
|
695 |
% littered with such conversion functions.
|
123
|
696 |
|
143
|
697 |
% In Scala you can do better by ``hiding'' the conversion
|
|
698 |
% functions. The keyword for doing this is \code{implicit} and
|
|
699 |
% it needs a built-in library called
|
123
|
700 |
|
143
|
701 |
% \begin{lstlisting}[numbers=none]
|
|
702 |
% scala.language.implicitConversions
|
|
703 |
% \end{lstlisting}
|
123
|
704 |
|
143
|
705 |
% \noindent
|
|
706 |
% Consider the code
|
123
|
707 |
|
|
708 |
|
143
|
709 |
% \begin{lstlisting}[language=Scala]
|
|
710 |
% import scala.language.implicitConversions
|
123
|
711 |
|
143
|
712 |
% def charlist2rexp(s: List[Char]) : Rexp = s match {
|
|
713 |
% case Nil => EMPTY
|
|
714 |
% case c::Nil => CHAR(c)
|
|
715 |
% case c::s => SEQ(CHAR(c), charlist2rexp(s))
|
|
716 |
% }
|
123
|
717 |
|
143
|
718 |
% implicit def string2rexp(s: String) : Rexp =
|
|
719 |
% charlist2rexp(s.toList)
|
|
720 |
% \end{lstlisting}
|
123
|
721 |
|
|
722 |
|
143
|
723 |
% \noindent where the first seven lines implement a function
|
|
724 |
% that given a list of characters generates the corresponding
|
|
725 |
% regular expression. In Lines 9 and 10, this function is used
|
|
726 |
% for transforming a string into a regular expression. Since the
|
|
727 |
% \code{string2rexp}-function is declared as \code{implicit},
|
|
728 |
% the effect will be that whenever Scala expects a regular
|
|
729 |
% expression, but I only give it a string, it will automatically
|
|
730 |
% insert a call to the \code{string2rexp}-function. I can now
|
|
731 |
% write for example
|
123
|
732 |
|
143
|
733 |
% \begin{lstlisting}[numbers=none]
|
|
734 |
% scala> ALT("ab", "ac")
|
|
735 |
% res9 = ALT(SEQ(CHAR(a),CHAR(b)),SEQ(CHAR(a),CHAR(c)))
|
|
736 |
% \end{lstlisting}
|
123
|
737 |
|
143
|
738 |
% \noindent Recall that \code{ALT} expects two regular
|
|
739 |
% expressions as arguments, but I only supply two strings. The
|
|
740 |
% implicit conversion function will transform the string into a
|
|
741 |
% regular expression.
|
123
|
742 |
|
143
|
743 |
% Using implicit definitions, Scala allows me to introduce
|
|
744 |
% some further syntactic sugar for regular expressions:
|
123
|
745 |
|
|
746 |
|
143
|
747 |
% \begin{lstlisting}[ numbers=none]
|
|
748 |
% implicit def RexpOps(r: Rexp) = new {
|
|
749 |
% def | (s: Rexp) = ALT(r, s)
|
|
750 |
% def ~ (s: Rexp) = SEQ(r, s)
|
|
751 |
% def % = STAR(r)
|
|
752 |
% }
|
123
|
753 |
|
143
|
754 |
% implicit def stringOps(s: String) = new {
|
|
755 |
% def | (r: Rexp) = ALT(s, r)
|
|
756 |
% def | (r: String) = ALT(s, r)
|
|
757 |
% def ~ (r: Rexp) = SEQ(s, r)
|
|
758 |
% def ~ (r: String) = SEQ(s, r)
|
|
759 |
% def % = STAR(s)
|
|
760 |
% }
|
|
761 |
% \end{lstlisting}
|
123
|
762 |
|
|
763 |
|
143
|
764 |
% \noindent This might seem a bit overly complicated, but its effect is
|
|
765 |
% that I can now write regular expressions such as $ab + ac$
|
|
766 |
% simply as
|
123
|
767 |
|
|
768 |
|
143
|
769 |
% \begin{lstlisting}[numbers=none]
|
|
770 |
% scala> "ab" | "ac"
|
|
771 |
% res10 = ALT(SEQ(CHAR(a),CHAR(b)),SEQ(CHAR(a),CHAR(c)))
|
|
772 |
% \end{lstlisting}
|
123
|
773 |
|
|
774 |
|
143
|
775 |
% \noindent I leave you to figure out what the other
|
|
776 |
% syntactic sugar in the code above stands for.
|
123
|
777 |
|
143
|
778 |
% One more useful feature of Scala is the ability to define
|
|
779 |
% functions with varying argument lists. This is a feature that
|
|
780 |
% is already present in old languages, like C, but seems to have
|
|
781 |
% been forgotten in the meantime---Java does not have it. In the
|
|
782 |
% context of regular expressions this feature comes in handy:
|
|
783 |
% Say you are fed up with writing many alternatives as
|
123
|
784 |
|
|
785 |
|
143
|
786 |
% \begin{lstlisting}[numbers=none]
|
|
787 |
% ALT(..., ALT(..., ALT(..., ...)))
|
|
788 |
% \end{lstlisting}
|
123
|
789 |
|
|
790 |
|
143
|
791 |
% \noindent To make it difficult, you do not know how deep such
|
|
792 |
% alternatives are nested. So you need something flexible that
|
|
793 |
% can take as many alternatives as needed. In Scala one can
|
|
794 |
% achieve this by adding a \code{*} to the type of an argument.
|
|
795 |
% Consider the code
|
123
|
796 |
|
|
797 |
|
143
|
798 |
% \begin{lstlisting}[language=Scala]
|
|
799 |
% def Alts(rs: List[Rexp]) : Rexp = rs match {
|
|
800 |
% case Nil => NULL
|
|
801 |
% case r::Nil => r
|
|
802 |
% case r::rs => ALT(r, Alts(rs))
|
|
803 |
% }
|
123
|
804 |
|
143
|
805 |
% def ALTS(rs: Rexp*) = Alts(rs.toList)
|
|
806 |
% \end{lstlisting}
|
123
|
807 |
|
|
808 |
|
143
|
809 |
% \noindent The function in Lines 1 to 5 takes a list of regular
|
|
810 |
% expressions and converts it into an appropriate alternative
|
|
811 |
% regular expression. In Line 7 there is a wrapper for this
|
|
812 |
% function which uses the feature of varying argument lists. The
|
|
813 |
% effect of this code is that I can write the regular
|
|
814 |
% expression for keywords as
|
123
|
815 |
|
|
816 |
|
143
|
817 |
% \begin{lstlisting}[numbers=none]
|
|
818 |
% ALTS("for", "def", "yield", "implicit", "if", "match", "case")
|
|
819 |
% \end{lstlisting}
|
123
|
820 |
|
|
821 |
|
143
|
822 |
% \noindent Again I leave it to you to find out how much this
|
|
823 |
% simplifies the regular expression in comparison with if I had
|
|
824 |
% to write this by hand using only the ``plain'' regular
|
|
825 |
% expressions from the inductive datatype.
|
|
826 |
|
|
827 |
\bigskip\noindent
|
|
828 |
\textit{More TBD.}
|
123
|
829 |
|
|
830 |
\subsection*{More Info}
|
|
831 |
|
|
832 |
There is much more to Scala than I can possibly describe in
|
|
833 |
this document. Fortunately there are a number of free books
|
|
834 |
about Scala and of course lots of help online. For example
|
|
835 |
|
|
836 |
\begin{itemize}
|
|
837 |
\item \url{http://www.scala-lang.org/docu/files/ScalaByExample.pdf}
|
|
838 |
\item \url{http://www.scala-lang.org/docu/files/ScalaTutorial.pdf}
|
|
839 |
\item \url{https://www.youtube.com/user/ShadowofCatron}
|
|
840 |
\item \url{http://docs.scala-lang.org/tutorials}
|
|
841 |
\item \url{https://www.scala-exercises.org}
|
|
842 |
\end{itemize}
|
|
843 |
|
|
844 |
\noindent There is also a course at Coursera on Functional
|
|
845 |
Programming Principles in Scala by Martin Odersky, the main
|
|
846 |
developer of the Scala language. And a document that explains
|
|
847 |
Scala for Java programmers
|
|
848 |
|
|
849 |
\begin{itemize}
|
|
850 |
\item \small\url{http://docs.scala-lang.org/tutorials/scala-for-java-programmers.html}
|
|
851 |
\end{itemize}
|
|
852 |
|
|
853 |
While I am quite enthusiastic about Scala, I am also happy to
|
|
854 |
admit that it has more than its fair share of faults. The
|
|
855 |
problem seen earlier of having to give an explicit type to
|
|
856 |
\code{toSet}, but not \code{toList} is one of them. There are
|
|
857 |
also many ``deep'' ideas about types in Scala, which even to
|
|
858 |
me as seasoned functional programmer are puzzling. Whilst
|
|
859 |
implicits are great, they can also be a source of great
|
|
860 |
headaches, for example consider the code:
|
|
861 |
|
|
862 |
\begin{lstlisting}[numbers=none]
|
|
863 |
scala> List (1, 2, 3) contains "your mom"
|
|
864 |
res1: Boolean = false
|
|
865 |
\end{lstlisting}
|
|
866 |
|
|
867 |
\noindent Rather than returning \code{false}, this code should
|
|
868 |
throw a typing-error. There are also many limitations Scala
|
|
869 |
inherited from the JVM that can be really annoying. For
|
|
870 |
example a fixed stack size. One can work around this
|
|
871 |
particular limitation, but why does one have to?
|
|
872 |
More such `puzzles' can be found at
|
|
873 |
|
|
874 |
\begin{center}
|
|
875 |
\url{http://scalapuzzlers.com} and
|
|
876 |
\url{http://latkin.org/blog/2017/05/02/when-the-scala-compiler-doesnt-help/}
|
|
877 |
\end{center}
|
|
878 |
|
|
879 |
Even if Scala has been a success in several high-profile
|
|
880 |
companies, there is also a company (Yammer) that first used
|
|
881 |
Scala in their production code, but then moved away from it.
|
|
882 |
Allegedly they did not like the steep learning curve of Scala
|
|
883 |
and also that new versions of Scala often introduced
|
|
884 |
incompatibilities in old code. In the past two months
|
|
885 |
there have also been two forks of the Scala compiler.
|
|
886 |
It needs to be seen what the future brings for Scala.
|
|
887 |
|
152
|
888 |
%So all in all, Scala might not be a great teaching language,
|
|
889 |
%but I hope this is mitigated by the fact that I never require
|
|
890 |
%you to write any Scala code. You only need to be able to read
|
|
891 |
%it. In the coursework you can use any programming language you
|
|
892 |
%like. If you want to use Scala for this, then be my guest; if
|
|
893 |
%you do not want, stick with the language you are most familiar
|
|
894 |
%with.
|
123
|
895 |
|
|
896 |
|
|
897 |
|
|
898 |
\end{document}
|
|
899 |
|
|
900 |
%%% Local Variables:
|
|
901 |
%%% mode: latex
|
|
902 |
%%% TeX-master: t
|
|
903 |
%%% End:
|