handouts/pep-ho.tex
changeset 271 48e12e7aee6e
parent 270 b9eaa5cdec4a
child 272 da3d30ae67ec
equal deleted inserted replaced
270:b9eaa5cdec4a 271:48e12e7aee6e
    39 % nice example for map and reduce using Harry potter characters
    39 % nice example for map and reduce using Harry potter characters
    40 % https://www.matthewgerstman.com/map-filter-reduce/
    40 % https://www.matthewgerstman.com/map-filter-reduce/
    41 
    41 
    42 
    42 
    43 \begin{document}
    43 \begin{document}
    44 \fnote{\copyright{} Christian Urban, King's College London, 2017, 2018}
    44 \fnote{\copyright{} Christian Urban, King's College London, 2017, 2018, 2019}
    45 
    45 
    46 \section*{A Crash-Course in Scala}
    46 \section*{A Crash-Course in Scala}
    47 
    47 
    48 \mbox{}\hfill\textit{``Scala --- \underline{S}lowly \underline{c}ompiled 
    48 \mbox{}\hfill\textit{``Scala --- \underline{S}lowly \underline{c}ompiled 
    49 \underline{a}cademic \underline{la}nguage''}\smallskip\\
    49 \underline{a}cademic \underline{la}nguage''}\smallskip\\
   242 is critical because you do not want that conflicting writes mess about
   242 is critical because you do not want that conflicting writes mess about
   243 with \texttt{i}. Take my word: an untold amount of misery has arisen
   243 with \texttt{i}. Take my word: an untold amount of misery has arisen
   244 from this problem. The catch is that if you try to solve this problem in
   244 from this problem. The catch is that if you try to solve this problem in
   245 C++ or Java, and be as defensive as possible about reads and writes to
   245 C++ or Java, and be as defensive as possible about reads and writes to
   246 \texttt{i}, then you need to synchronise access to it. The result is that
   246 \texttt{i}, then you need to synchronise access to it. The result is that
   247 your program more often than not waits more than it runs, thereby
   247 very often your program waits more than it runs, thereby
   248 defeating the point of trying to run the program in parallel in the
   248 defeating the point of trying to run the program in parallel in the
   249 first place. If you are less defensive, then usually all hell breaks
   249 first place. If you are less defensive, then usually all hell breaks
   250 loose by seemingly obtaining random results. And forget the idea of
   250 loose by seemingly obtaining random results. And forget the idea of
   251 being able to debug such code.
   251 being able to debug such code.
   252 
   252 
   371 programs. Once you installed Scala, you can start the interpreter by
   371 programs. Once you installed Scala, you can start the interpreter by
   372 typing on the command line:
   372 typing on the command line:
   373 
   373 
   374 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   374 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   375 $ scala
   375 $ scala
   376 Welcome to Scala 2.12.7 (Java HotSpot(TM) 64-Bit Server VM, Java 9).
   376 Welcome to Scala 2.13.0 (Java HotSpot(TM) 64-Bit Server VM, Java 9).
   377 Type in expressions for evaluation. Or try :help.
   377 Type in expressions for evaluation. Or try :help.
   378 
   378 
   379 scala>
   379 scala>
   380 \end{lstlisting}%$
   380 \end{lstlisting}%$
   381 
   381 
   486 \subsection*{Values}
   486 \subsection*{Values}
   487 
   487 
   488 In the lectures I will try to avoid as much as possible the term
   488 In the lectures I will try to avoid as much as possible the term
   489 \emph{variables} familiar from other programming languages. The reason
   489 \emph{variables} familiar from other programming languages. The reason
   490 is that Scala has \emph{values}, which can be seen as abbreviations of
   490 is that Scala has \emph{values}, which can be seen as abbreviations of
   491 larger expressions. For example
   491 larger expressions. The keyword for defining values is \code{val}.
       
   492 For example
   492 
   493 
   493 \begin{lstlisting}[numbers=none]
   494 \begin{lstlisting}[numbers=none]
   494 scala> val x = 42
   495 scala> val x = 42
   495 x: Int = 42
   496 x: Int = 42
   496 
   497 
   500 scala> val z = x / y
   501 scala> val z = x / y
   501 z: Int = 6
   502 z: Int = 6
   502 \end{lstlisting}
   503 \end{lstlisting}
   503 
   504 
   504 \noindent
   505 \noindent
   505 Why the kerfuffle about values? Well, values are \emph{immutable}. You 
   506 As can be seen we first define \code{x} and {y} with some silly
   506 cannot change their value after you defined them. If you try to reassign
   507 expressions, and then reuse these values in the definition of \code{z}.
   507 \code{z} above, Scala will yell at you:
   508 All easy, no? Why the kerfuffle about values? Well, values are
       
   509 \emph{immutable}. You cannot change their value after you defined them.
       
   510 If you try to reassign \code{z} above, Scala will yell at you:
   508 
   511 
   509 \begin{lstlisting}[numbers=none]
   512 \begin{lstlisting}[numbers=none]
   510 scala> z = 9
   513 scala> z = 9
   511 error: reassignment to val
   514 error: reassignment to val
   512        z = 9
   515        z = 9
   526 
   529 
   527 \noindent but try to guess what Scala will print out 
   530 \noindent but try to guess what Scala will print out 
   528 for \code{z}?  Will it be \code{6} or \code{10}? A final word about
   531 for \code{z}?  Will it be \code{6} or \code{10}? A final word about
   529 values: Try to stick to the convention that names of values should be
   532 values: Try to stick to the convention that names of values should be
   530 lower case, like \code{x}, \code{y}, \code{foo41} and so on. Upper-case
   533 lower case, like \code{x}, \code{y}, \code{foo41} and so on. Upper-case
   531 names you should reserve for what is called \emph{constructors}.
   534 names you should reserve for what is called \emph{constructors}. And 
       
   535 forgive me when I call values as variables\ldots{}it is just something that
       
   536 has been in imprinted into my developer-DNA during my early days and
       
   537 difficult to get rid of.~\texttt{;o)}  
   532 
   538 
   533 
   539 
   534 \subsection*{Function Definitions}
   540 \subsection*{Function Definitions}
   535 
   541 
   536 We do functional programming! So defining functions will be our main occupation.
   542 We do functional programming! So defining functions will be our main occupation.
   541 def f(x: Int) : String = ...EXPR...
   547 def f(x: Int) : String = ...EXPR...
   542 \end{lstlisting} 
   548 \end{lstlisting} 
   543 
   549 
   544 \noindent
   550 \noindent
   545 This function returns the value resulting from evaluating the expression
   551 This function returns the value resulting from evaluating the expression
   546 \code{EXPR} (whatever is substituted for this). The result will be
   552 \code{EXPR} (whatever is substituted for this). Since we declared
   547 of type \code{String}. It is a good habit to always include this information
   553 \code{String}, the result of this function will be of type
       
   554 \code{String}. It is a good habit to always include this information
   548 about the return type. Simple examples of Scala functions are:
   555 about the return type. Simple examples of Scala functions are:
   549 
   556 
   550 \begin{lstlisting}[numbers=none]
   557 \begin{lstlisting}[numbers=none]
   551 def incr(x: Int) : Int = x + 1
   558 def incr(x: Int) : Int = x + 1
   552 def double(x: Int) : Int = x + x
   559 def double(x: Int) : Int = x + x
   556 \noindent
   563 \noindent
   557 The general scheme for a function is
   564 The general scheme for a function is
   558 
   565 
   559 \begin{lstlisting}[numbers=none]
   566 \begin{lstlisting}[numbers=none]
   560 def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
   567 def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
   561   BODY
   568   ...BODY...
   562 }
   569 }
   563 \end{lstlisting}
   570 \end{lstlisting}
   564 
   571 
   565 \noindent
   572 \noindent
   566 where each argument, \texttt{arg1}, \texttt{arg2} and so on, requires 
   573 where each argument, \texttt{arg1}, \texttt{arg2} and so on, requires 
   570 is just a simple expression, like \code{x + 1}, you can omit the
   577 is just a simple expression, like \code{x + 1}, you can omit the
   571 braces. Very often functions are recursive (that is call themselves),
   578 braces. Very often functions are recursive (that is call themselves),
   572 like the venerable factorial function:
   579 like the venerable factorial function:
   573 
   580 
   574 \begin{lstlisting}[numbers=none]
   581 \begin{lstlisting}[numbers=none]
   575 def fact(n: Int): Int = 
   582 def fact(n: Int) : Int = 
   576   if (n == 0) 1 else n * fact(n - 1)
   583   if (n == 0) 1 else n * fact(n - 1)
   577 \end{lstlisting}
   584 \end{lstlisting}
   578 
   585 
   579 \noindent
   586 \noindent
       
   587 We could also have written this as
       
   588 
       
   589 \begin{lstlisting}[numbers=none]
       
   590 def fact(n: Int) : Int = {
       
   591   if (n == 0) 1 
       
   592   else n * fact(n - 1)
       
   593 }    
       
   594 \end{lstlisting}
       
   595 
       
   596 \noindent
       
   597 but this seems a bit over-kill for a small function like \code{fact}.
   580 Note that Scala does not have a \code{then}-keyword in an \code{if}-statement.
   598 Note that Scala does not have a \code{then}-keyword in an \code{if}-statement.
   581   
   599 Note also that there are a few other ways of how to define a function. We 
       
   600 will see some in the next sections.
       
   601 
   582 \subsection*{Loops, or better the Absence thereof}
   602 \subsection*{Loops, or better the Absence thereof}
   583 
   603 
   584 Coming from Java or C++, you might be surprised that Scala does
   604 Coming from Java or C++, you might be surprised that Scala does
   585 not really have loops. It has instead, what is in functional
   605 not really have loops. It has instead, what is in functional
   586 programming called, \emph{maps}. To illustrate how they work,
   606 programming called, \emph{maps}. To illustrate how they work,
   695 \end{lstlisting}
   715 \end{lstlisting}
   696 
   716 
   697 \noindent The \code{if}-condition in the for-comprehension
   717 \noindent The \code{if}-condition in the for-comprehension
   698 filters out all pairs where the sum is not even.
   718 filters out all pairs where the sum is not even.
   699 
   719 
   700 While hopefully this all looks reasonable, there is one
   720 \subsection*{Results and Side-Effects}
       
   721 
       
   722 While hopefully this all about maps looks reasonable, there is one
   701 complication: In the examples above we always wanted to
   723 complication: In the examples above we always wanted to
   702 transform one list into another list (e.g.~list of squares),
   724 transform one list into another list (e.g.~list of squares),
   703 or one set into another set (set of numbers into set of
   725 or one set into another set (set of numbers into set of
   704 remainders modulo 3). What happens if we just want to print out
   726 remainders modulo 3). What happens if we just want to print out
   705 a list of integers? Then actually the for-comprehension
   727 a list of integers? Then actually the for-comprehension
   763 If you want to find out more about maps and functions with
   785 If you want to find out more about maps and functions with
   764 side-effects, you can ponder about the response Scala gives if
   786 side-effects, you can ponder about the response Scala gives if
   765 you replace \code{foreach} by \code{map} in the expression
   787 you replace \code{foreach} by \code{map} in the expression
   766 above. Scala will still allow \code{map} with side-effect
   788 above. Scala will still allow \code{map} with side-effect
   767 functions, but then reacts with a slightly interesting result.
   789 functions, but then reacts with a slightly interesting result.
       
   790 
       
   791 \subsection*{Higher-Order Functions}
   768 
   792 
   769 \subsection*{Types}
   793 \subsection*{Types}
   770 
   794 
   771 In most functional programming languages, types play an
   795 In most functional programming languages, types play an
   772 important role. Scala is such a language. You have already
   796 important role. Scala is such a language. You have already