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