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