handouts/pep-ho.tex
changeset 188 937c995b047a
parent 187 4d300409f2fe
child 189 ff815ca0bbcf
child 192 a112e0e2325c
equal deleted inserted replaced
187:4d300409f2fe 188:937c995b047a
    32 have a native Scala compiler generating X86-code
    32 have a native Scala compiler generating X86-code
    33 (\url{http://www.scala-native.org}).} Because of this it has also access to
    33 (\url{http://www.scala-native.org}).} Because of this it has also access to
    34 the myriads of Java libraries. Unlike Java, however, Scala often allows
    34 the myriads of Java libraries. Unlike Java, however, Scala often allows
    35 programmers to write very concise and elegant code.  Some therefore say
    35 programmers to write very concise and elegant code.  Some therefore say
    36 ``Scala is the better Java''.\footnote{from
    36 ``Scala is the better Java''.\footnote{from
    37 \url{https://www.slideshare.net/maximnovak/joy-of-scala}} A number
    37 \url{https://www.slideshare.net/maximnovak/joy-of-scala}} 
    38 of companies---the Guardian, Twitter, Coursera, FourSquare, LinkedIn,
    38 
    39 Netflix to name a few---either use Scala exclusively in production code,
    39 A number of companies---the Guardian, Twitter, Coursera, FourSquare, Netflix,
    40 or at least to some substantial degree. Scala seems also useful in
    40 LinkedIn to name a few---either use Scala exclusively in
    41 job-interviews (especially in data science) according to this anecdotal
    41 production code, or at least to some substantial degree. Scala seems
    42 report
    42 also useful in job-interviews (especially in data science) according to
       
    43 this anecdotal report
    43 
    44 
    44 \begin{quote}
    45 \begin{quote}
    45 \url{http://techcrunch.com/2016/06/14/scala-is-the-new-golden-child}
    46 \url{http://techcrunch.com/2016/06/14/scala-is-the-new-golden-child}
    46 \end{quote}
    47 \end{quote}
    47 
    48 
   120 C++\ldots{}the world should be your oyster, no? Well, it is not that
   121 C++\ldots{}the world should be your oyster, no? Well, it is not that
   121 easy. We do require Scala in PEP, but actually we do not religiously
   122 easy. We do require Scala in PEP, but actually we do not religiously
   122 care whether you learn Scala---after all it is just a programming
   123 care whether you learn Scala---after all it is just a programming
   123 language (albeit a nifty one IMHO). What we do care about is that you
   124 language (albeit a nifty one IMHO). What we do care about is that you
   124 learn about \textit{functional programming}. Scala is just the vehicle
   125 learn about \textit{functional programming}. Scala is just the vehicle
   125 for that. Still you need to learn Scala well enough to get good grades
   126 for that. Still, you need to learn Scala well enough to get good marks
   126 in PEP, but functional programming could equally be taught with Haskell,
   127 in PEP, but functional programming could equally be taught with Haskell,
   127 F\#, SML, Ocaml, Kotlin, Scheme, Elm and many other functional
   128 F\#, SML, Ocaml, Kotlin, Clojure, Scheme, Elm and many other functional
   128 programming languages. %Your friendly lecturer just happens to like Scala
   129 programming languages. %Your friendly lecturer just happens to like Scala
   129 %and the Department agreed that it is a good idea to inflict Scala upon
   130 %and the Department agreed that it is a good idea to inflict Scala upon
   130 %you.
   131 %you.
   131 
   132 
   132 Very likely writing programs in a functional programming language is
   133 Very likely writing programs in a functional programming language is
   149 \noindent Here the integer variable \texttt{i} embodies the state, which
   150 \noindent Here the integer variable \texttt{i} embodies the state, which
   150 is first set to \texttt{10} and then increased by one in each
   151 is first set to \texttt{10} and then increased by one in each
   151 loop-iteration until it reaches \texttt{20} at which point the loop
   152 loop-iteration until it reaches \texttt{20} at which point the loop
   152 exits. When this code is compiled and actually runs, there will be some
   153 exits. When this code is compiled and actually runs, there will be some
   153 dedicated space reserved for \texttt{i} in memory. This space of
   154 dedicated space reserved for \texttt{i} in memory. This space of
   154 typically 32 bits contains its current value\ldots\texttt{10} at the
   155 typically 32 bits contains \texttt{i}'s current value\ldots\texttt{10}
   155 beginning, and then the content will be updated by, or overwritten with,
   156 at the beginning, and then the content will be updated by, or
   156 some new content in every iteration. The main point here is that this
   157 overwritten with, some new content in every iteration. The main point
   157 kind of updating, or manipulating, memory is 25.806\ldots or \textbf{THE
   158 here is that this kind of updating, or manipulating, memory is
   158 ROOT OF ALL EVIL}!!
   159 25.806\ldots or \textbf{THE ROOT OF ALL EVIL}!!
   159 
   160 
   160 \begin{center}
   161 \begin{center}
   161 \includegraphics[scale=0.25]{../pics/root-of-all-evil.png}
   162 \includegraphics[scale=0.25]{../pics/root-of-all-evil.png}
   162 \end{center}  
   163 \end{center}  
   163 
   164 
   213 \texttt{.par}. Try the same in C++ or Java!
   214 \texttt{.par}. Try the same in C++ or Java!
   214 
   215 
   215 \begin{figure}[p]
   216 \begin{figure}[p]
   216 \begin{boxedminipage}{\textwidth}
   217 \begin{boxedminipage}{\textwidth}
   217 
   218 
   218 A Scala programm for generating pretty pictures of the Mandelbrot Set 
   219 A Scala program for generating pretty pictures of the Mandelbrot set 
   219 (\url{https://en.wikipedia.org/wiki/Mandelbrot_set}):
   220 (\url{https://en.wikipedia.org/wiki/Mandelbrot_set},
       
   221 \url{https://www.youtube.com/watch?v=aSg2Db3jF_4}):
   220 \begin{center}    
   222 \begin{center}    
   221 \begin{tabular}{c}  
   223 \begin{tabular}{c}  
   222 \includegraphics[scale=0.12]{../pics/mand1.png}
   224 \includegraphics[scale=0.12]{../pics/mand1.png}
   223 \end{tabular}
   225 \end{tabular}
   224 \end{center}
   226 \end{center}
   225 
   227 
   226 \begin{center}
   228 \begin{center}
   227 \begin{tabular}{@{}p{0.45\textwidth}|p{0.45\textwidth}@{}}
   229 \begin{tabular}{@{}p{0.45\textwidth}|p{0.45\textwidth}@{}}
   228   \bf sequential version: & \bf parallel version: (on 4 cores)\smallskip\\
   230   \bf sequential version: & \bf parallel version (on 4 cores):\smallskip\\
   229 
   231 
   230   {\hfill\includegraphics[scale=0.12]{../pics/mand4.png}\hfill} &
   232   {\hfill\includegraphics[scale=0.12]{../pics/mand4.png}\hfill} &
   231   {\hfill\includegraphics[scale=0.12]{../pics/mand3.png}\hfill} \\
   233   {\hfill\includegraphics[scale=0.12]{../pics/mand3.png}\hfill} \\
   232 
   234 
   233 {\footnotesize\begin{lstlisting}[xleftmargin=-1mm]
   235 {\footnotesize\begin{lstlisting}[xleftmargin=-1mm]
   246   viewer.updateUI()
   248   viewer.updateUI()
   247 }   
   249 }   
   248 \end{lstlisting}}   
   250 \end{lstlisting}}   
   249 & 
   251 & 
   250 {\footnotesize\begin{lstlisting}[xleftmargin=0mm]
   252 {\footnotesize\begin{lstlisting}[xleftmargin=0mm]
   251 for (y <- (0 until H).par) {
   253 for (y <- (0 until H)/*@\keys{\texttt{.par}}@*/) {
   252   for (x <- (0 until W).par) {
   254   for (x <- (0 until W)/*@\keys{\texttt{.par}}@*/) {
   253       
   255       
   254     val c = start + 
   256     val c = start + 
   255       (x * d_x + y * d_y * i)
   257       (x * d_x + y * d_y * i)
   256     val iters = iterations(c, max) 
   258     val iters = iterations(c, max) 
   257     val col = 
   259     val col = 
   263   viewer.updateUI()
   265   viewer.updateUI()
   264 }   
   266 }   
   265 \end{lstlisting}}\\
   267 \end{lstlisting}}\\
   266 
   268 
   267 \centering\includegraphics[scale=0.5]{../pics/cpu2.png} &
   269 \centering\includegraphics[scale=0.5]{../pics/cpu2.png} &
   268 \centering\includegraphics[scale=0.5]{../pics/cpu1.png}\\ 
   270 \centering\includegraphics[scale=0.5]{../pics/cpu1.png}
   269 
       
   270 
       
   271 \end{tabular}
   271 \end{tabular}
   272 \end{center}
   272 \end{center}
   273 \caption{Test \label{mand}} 
   273 \caption{The main ``loops'' creating the picture of the Mandelbrot set. The parallel version
       
   274 only differs in \texttt{.par} added to the ``ranges'' of the x-y-coordinates. As can be
       
   275 seen from the CPU loads: in the sequential versions there is a lower peak for an
       
   276 extended period, while in the parallel version there is a short sharp burst for 
       
   277 essentially the same workload.
       
   278 \label{mand}} 
   274 \end{boxedminipage}
   279 \end{boxedminipage}
   275 \end{figure}  
   280 \end{figure}  
   276 
   281 
   277 But remember that this easy parallelisation of code requires that we
   282 But remember this easy parallelisation of code requires that we
   278 have no state in our programs\ldots{} that is no counters like
   283 have no state in our programs\ldots{}that is no counters like
   279 \texttt{i} in \texttt{for}-loops. You might then ask, how do I write
   284 \texttt{i} in \texttt{for}-loops. You might then ask, how do I write
   280 loops without such counters? Well, teaching you that this is possible is
   285 loops without such counters? Well, teaching you that this is possible is
   281 one of the main points of the Scala-part in PEP. I can assure you it is
   286 one of the main points of the Scala-part in PEP. I can assure you it is
   282 possible, but you have to get your head around it. Once you have
   287 possible, but you have to get your head around it. Once you have
   283 mastered this, it will be fun to have no state in your programs (a side
   288 mastered this, it will be fun to have no state in your programs (a side
   284 product is that it much easier to debug state-less code and also more
   289 product is that it much easier to debug state-less code and also more
   285 often than not easier to understand). So good luck with
   290 often than not easier to understand). So have fun with
   286 Scala!\footnote{If you are still not convinced about the function
   291 Scala!\footnote{If you are still not convinced about the function
   287 programming ``thing'', there are a few more arguments: a lot of research
   292 programming ``thing'', there are a few more arguments: a lot of research
   288 in programming languages happens to take place in functional programming
   293 in programming languages happens to take place in functional programming
   289 languages. This has resulted in ultra-useful features such as
   294 languages. This has resulted in ultra-useful features such as
   290 pattern-matching, strong type-systems, lazyness, implicits, algebraic
   295 pattern-matching, strong type-systems, lazyness, implicits, algebraic
   291 datatypes  to name a few. Imperative languages seem to always lag behind
   296 datatypes  to name a few. Imperative languages seem to often lag behind
   292 in adopting them: I know, for example, that Java will at some point in
   297 in adopting them: I know, for example, that Java will at some point in
   293 the future support pattern-matching, which has been used in SML for at
   298 the future support pattern-matching, which has been used in SML for at
   294 least 40(!) years. See
   299 least 40(!) years. See
   295 \url{http://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html}.
   300 \url{http://cr.openjdk.java.net/~briangoetz/amber/pattern-match.html}.
   296 Also Rust, a C-like programming language that has been developed since
   301 Also Rust, a C-like programming language that has been developed since
   297 2010 and is gaining quite some interest, borrows many ideas from
   302 2010 and is gaining quite some interest, borrows many ideas from
   298 functional programming from yesteryear.}
   303 functional programming from yesteryear.}
   299 
   304 
       
   305 
   300 \subsection*{The Very Basics}
   306 \subsection*{The Very Basics}
   301 
   307 
   302 One advantage of Scala over Java is that it includes an interpreter (a
   308 One advantage of Scala over Java is that it includes an interpreter (a
   303 REPL, or
   309 REPL, or
   304 \underline{R}ead-\underline{E}val-\underline{P}rint-\underline{L}oop)
   310 \underline{R}ead-\underline{E}val-\underline{P}rint-\underline{L}oop)
   305 with which you can run and test small code snippets without the need
   311 with which you can run and test small code snippets without the need
   306 of a compiler. This helps a lot with interactively developing
   312 of a compiler. This helps a lot with interactively developing
   307 programs. This is really my preferred way of writing small Scala
   313 programs. It is my preferred way of writing small Scala
   308 programs. Once you installed Scala, you can start the interpreter by
   314 programs. Once you installed Scala, you can start the interpreter by
   309 typing on the command line:
   315 typing on the command line:
   310 
   316 
   311 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   317 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   312 $ scala
   318 $ scala
   324 \begin{lstlisting}[numbers=none]
   330 \begin{lstlisting}[numbers=none]
   325 scala> 2 + 3
   331 scala> 2 + 3
   326 res0: Int = 5
   332 res0: Int = 5
   327 \end{lstlisting}
   333 \end{lstlisting}
   328 
   334 
   329 \noindent indicating that the result of the addition is of type
   335 \noindent The answer means that he result of the addition is of type
   330 \code{Int} and the actual result is 5; \code{res0} is a name that
   336 \code{Int} and the actual result is 5; \code{res0} is a name that
   331 Scala gives automatically to the result. You can reuse this name later
   337 Scala gives automatically to the result. You can reuse this name later
   332 on. 
   338 on, for example
   333 
   339 
   334 \begin{lstlisting}[numbers=none]
   340 \begin{lstlisting}[numbers=none]
   335 scala> res0 + 4
   341 scala> res0 + 4
   336 res1: Int = 9
   342 res1: Int = 9
   337 \end{lstlisting}
   343 \end{lstlisting}
   352 programming-style, you will know what the difference is
   358 programming-style, you will know what the difference is
   353 between a function that returns a result, like addition, and a
   359 between a function that returns a result, like addition, and a
   354 function that causes a side-effect, like \code{print}. We
   360 function that causes a side-effect, like \code{print}. We
   355 shall come back to this point later, but if you are curious
   361 shall come back to this point later, but if you are curious
   356 now, the latter kind of functions always has \code{Unit} as
   362 now, the latter kind of functions always has \code{Unit} as
   357 return type. It is just not printed.
   363 return type. It is just not printed by Scala. 
   358 
   364 
   359 You can try more examples with the Scala REPL, but feel free to
   365 You can try more examples with the Scala REPL, but feel free to
   360 first guess what the result is (not all answers by Scala are obvious):
   366 first guess what the result is (not all answers by Scala are obvious):
   361 
   367 
   362 \begin{lstlisting}[numbers=none]
   368 \begin{lstlisting}[numbers=none]
   389     println("hello world")
   395     println("hello world")
   390 }
   396 }
   391 \end{lstlisting}
   397 \end{lstlisting}
   392 
   398 
   393 \noindent save it in a file, for example {\tt hello-world.scala}, and
   399 \noindent save it in a file, for example {\tt hello-world.scala}, and
   394 then run the compiler (\texttt{scalac}) and followed by the runtime
   400 then run the compiler (\texttt{scalac}) and start the runtime
   395 environment (\texttt{scala}):
   401 environment (\texttt{scala}):
   396 
   402 
   397 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   403 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   398 $ scalac hello-world.scala
   404 $ scalac hello-world.scala
   399 $ scala Hello
   405 $ scala Hello
   458 \end{lstlisting}
   464 \end{lstlisting}
   459 
   465 
   460 \noindent but try to guess what Scala will print out 
   466 \noindent but try to guess what Scala will print out 
   461 for \code{z}?  Will it be \code{6} or \code{10}? A final word about
   467 for \code{z}?  Will it be \code{6} or \code{10}? A final word about
   462 values: Try to stick to the convention that names of values should be
   468 values: Try to stick to the convention that names of values should be
   463 lower case, like \code{x}, \code{y}, \code{foo41} and so on.
   469 lower case, like \code{x}, \code{y}, \code{foo41} and so on. Upper-case
       
   470 names you should reserve for what is called \emph{constructors}.
   464 
   471 
   465 
   472 
   466 \subsection*{Function Definitions}
   473 \subsection*{Function Definitions}
   467 
   474 
   468 We do functional programming! So defining functions will be our main occupation.
   475 We do functional programming! So defining functions will be our main occupation.
   498 where each argument requires its type and the result type of the
   505 where each argument requires its type and the result type of the
   499 function, \code{rty}, should be given. If the body of the function is
   506 function, \code{rty}, should be given. If the body of the function is
   500 more complex, then it can be enclosed in braces, like above. If it it
   507 more complex, then it can be enclosed in braces, like above. If it it
   501 is just a simple expression, like \code{x + 1}, you can omit the
   508 is just a simple expression, like \code{x + 1}, you can omit the
   502 braces. Very often functions are recursive (call themselves) like
   509 braces. Very often functions are recursive (call themselves) like
   503 the venerable factorial function.
   510 the venerable factorial function:
   504 
   511 
   505 \begin{lstlisting}[numbers=none]
   512 \begin{lstlisting}[numbers=none]
   506 def fact(n: Int): Int = 
   513 def fact(n: Int): Int = 
   507   if (n == 0) 1 else n * fact(n - 1)
   514   if (n == 0) 1 else n * fact(n - 1)
   508 \end{lstlisting}
   515 \end{lstlisting}
       
   516 
       
   517 \noindent
       
   518 Note that Scala does not have a \code{then}-keyword in an \code{if}-statement.
   509   
   519   
   510 \subsection*{Loops, or better the Absence thereof}
   520 \subsection*{Loops, or better the Absence thereof}
   511 
   521 
   512 Coming from Java or C++, you might be surprised that Scala does
   522 Coming from Java or C++, you might be surprised that Scala does
   513 not really have loops. It has instead, what is in functional
   523 not really have loops. It has instead, what is in functional
  1084 \item \url{http://www.scala-lang.org/docu/files/ScalaByExample.pdf}
  1094 \item \url{http://www.scala-lang.org/docu/files/ScalaByExample.pdf}
  1085 \item \url{http://www.scala-lang.org/docu/files/ScalaTutorial.pdf}
  1095 \item \url{http://www.scala-lang.org/docu/files/ScalaTutorial.pdf}
  1086 \item \url{https://www.youtube.com/user/ShadowofCatron}
  1096 \item \url{https://www.youtube.com/user/ShadowofCatron}
  1087 \item \url{http://docs.scala-lang.org/tutorials}
  1097 \item \url{http://docs.scala-lang.org/tutorials}
  1088 \item \url{https://www.scala-exercises.org}
  1098 \item \url{https://www.scala-exercises.org}
       
  1099 \item \url{https://twitter.github.io/scala_school}
  1089 \end{itemize}
  1100 \end{itemize}
  1090 
  1101  
  1091 \noindent There is also a course at Coursera on Functional
  1102 \noindent There is also a course at Coursera on Functional
  1092 Programming Principles in Scala by Martin Odersky, the main
  1103 Programming Principles in Scala by Martin Odersky, the main
  1093 developer of the Scala language. And a document that explains
  1104 developer of the Scala language. And a document that explains
  1094 Scala for Java programmers
  1105 Scala for Java programmers
  1095 
  1106