handouts/pep-ho.tex
changeset 181 31ba76ce016d
parent 180 35b4dc785a40
child 182 d3d912d7e17f
equal deleted inserted replaced
180:35b4dc785a40 181:31ba76ce016d
     4 \usepackage{marvosym}
     4 \usepackage{marvosym}
     5 
     5 
     6 %cheat sheet
     6 %cheat sheet
     7 %http://worldline.github.io/scala-cheatsheet/
     7 %http://worldline.github.io/scala-cheatsheet/
     8 
     8 
     9 % case class, apply, unappy
     9 % case class, apply, unapply
    10 % see https://medium.com/@thejasbabu/scala-pattern-matching-9c9e73ba9a8a
    10 % see https://medium.com/@thejasbabu/scala-pattern-matching-9c9e73ba9a8a
    11 
    11 
    12 \begin{document}
    12 \begin{document}
    13 \fnote{\copyright{} Christian Urban, King's College London, 2017, 2018}
    13 \fnote{\copyright{} Christian Urban, King's College London, 2017, 2018}
    14 
    14 
    15 \section*{A Crash-Course in Scala}
    15 \section*{A Crash-Course in Scala}
    16 
    16 
    17 \mbox{}\hfill\textit{``Scala --- Slowly Compiled Academic LAnguage''}\\
    17 \mbox{}\hfill\textit{``Scala --- \underline{S}lowly \underline{C}ompiled 
       
    18 \underline{A}cademic \underline{LA}nguage''}\smallskip\\
    18 \mbox{}\hfill\textit{ --- a joke read on Twitter}\bigskip
    19 \mbox{}\hfill\textit{ --- a joke read on Twitter}\bigskip
    19  
    20  
    20 \noindent
    21 \noindent
    21 Scala is a programming language that combines functional and
    22 Scala is a programming language that combines functional and
    22 object-oriented programming-styles. It has received quite a bit of
    23 object-oriented programming-styles. It has received quite a bit of
    23 attention in the last five or so years. One reason for this attention
    24 attention in the last five or so years. One reason for this attention is
    24 is that, like the Java programming language, Scala compiles to the
    25 that, like the Java programming language, Scala compiles to the Java
    25 Java Virtual Machine (JVM) and therefore Scala programs can run under
    26 Virtual Machine (JVM) and therefore Scala programs can run under MacOSX,
    26 MacOSX, Linux and Windows.\footnote{There are also experimental
    27 Linux and Windows.\footnote{There are also experimental backends for
    27   backends for Android and JavaScript; and also work is under way to
    28 producing code under Android (\url{http://scala-android.org}); and also
    28   have a native compiler, see
    29 for generating JavaScript code to build browser applications
    29   \url{https://github.com/scala-native/scala-native}.} Unlike Java,
    30 \url{(https://www.scala-js.org)}. Moreover there is work under way to
    30 however, Scala often allows programmers to write very concise and
    31 have a native Scala compiler generating X86-code
    31 elegant code.  Some therefore say: ``Scala is the better
    32 (\url{http://www.scala-native.org}).} It therefore has also access to
    32 Java''.\footnote{\url{https://www.slideshare.net/maximnovak/joy-of-scala}}
    33 the myriads of Java libraries. Unlike Java, however, Scala often allows
    33 Also a number of companies (the Guardian, Twitter, Coursera,
    34 programmers to write very concise and elegant code.  Some therefore say:
    34 FourSquare, LinkedIn to name a few) either use Scala exclusively in
    35 ``Scala is the better Java''.\footnote{form
    35 production code, or at least to some substantial degree. Scala seems
    36 \url{https://www.slideshare.net/maximnovak/joy-of-scala}} Also a number
    36 also to be useful in job-interviews (in Data Science) according to
    37 of companies---the Guardian, Twitter, Coursera, FourSquare, LinkedIn,
    37 this anecdotal report
    38 Netflix to name a few---either use Scala exclusively in production code,
    38 
    39 or at least to some substantial degree. Scala seems also to be useful in
    39 \begin{quote}\small
    40 job-interviews (especially in Data Science) according to this anecdotal
    40 \url{https://techcrunch.com/2016/06/14/scala-is-the-new-golden-child/}
    41 report
       
    42 
       
    43 \begin{quote}
       
    44 \url{http://techcrunch.com/2016/06/14/scala-is-the-new-golden-child}
    41 \end{quote}
    45 \end{quote}
    42 
    46 
    43 \noindent
    47 \noindent
    44 The official Scala compiler can be downloaded from
    48 The official Scala compiler can be downloaded from
    45 
    49 
    46 \begin{quote}
    50 \begin{quote}
    47 \url{http://www.scala-lang.org}
    51 \url{http://www.scala-lang.org}
    48 \end{quote}
    52 \end{quote}
    49 
    53 
    50 \noindent
    54 \noindent
    51 A ready-made bundle with the Eclipse IDE is at
    55 I found a convenient IDE for Scala programming is Microsoft's
       
    56 \textit{Visual Studio Code} (VS Code) which runs under MacOSX, Linux and
       
    57 obviously Windows. It can be downloaded for free from
    52 
    58 
    53 \begin{quote}
    59 \begin{quote}
    54 \url{http://scala-ide.org/download/sdk.html}
    60 \url{https://code.visualstudio.com}
    55 \end{quote}
    61 \end{quote}
    56 
    62 
    57 \noindent
    63 \noindent
    58 When developing Scala programs, I personally prefer to use Emacs
    64 and should already come pre-installed in the Department (together with
    59 or Sublime as my environment, since they provide an easy access
    65 the Scala compiler). VS Code includes a \textit{Marketplace} from which 
    60 to the Scala REPL (see below).  But it is also possible to work
    66 a multitude of extensions can be downloaded that make editing and 
    61 completely on the command line and also with heavy-duty IDEs
    67 running Scala code easier (see Figure~\ref{vscode}).
    62 like Eclipse of IntelliJ. There is even an online editor and
    68 
    63 environment for developing Scala programs called ScalaFiddle
    69 \begin{figure}[t]
    64 
    70 \begin{center}  
       
    71 \includegraphics[scale=0.15]{../pics/vscode.png}\\[-10mm]\mbox{}
       
    72 \end{center}
       
    73 \caption{My personal installation of VS Code includes the following packages
       
    74 from Marketplace: Scala Syntax (official), Code Runner, Code Spell Checker,
       
    75 Rewrap and Subtle Match Brackets. I have also bound keys \keys{\^{}} \keys{Ret}
       
    76 to the action ``Run-Selected-Text-In-Active-Terminal'' in order to 
       
    77 quickly evaluate small code snippets in the Scala REPL.\label{vscode}}
       
    78 \end{figure}  
       
    79 
       
    80 What I like most about VS Code is that it provides an easy access to the
       
    81 Scala REPL. But if you prefer your own editor for coding, it
       
    82 is also easy to work with Scala completely on the command line (like you
       
    83 might have done with \texttt{g++} in the earlier part of PEP). For the
       
    84 lazybones among us, there is even an online editor and environment for
       
    85 developing and running Scala programs called \textit{ScalaFiddle}, which
       
    86 requires zero setup (assuming you have a browser handy)
       
    87  
    65 \begin{quote}
    88 \begin{quote}
    66 \url{https://scalafiddle.io}
    89 \url{https://scalafiddle.io}
    67 \end{quote}
    90 \end{quote}
    68   
    91   
    69 
    92 
    70 
    93 Scala can also be used with the heavy-duty IDEs Eclipse and IntelliJ.
       
    94 A ready-made Scala bundle for Eclipse is available at
       
    95 
       
    96 \begin{quote}
       
    97 \url{http://scala-ide.org/download/sdk.html}
       
    98 \end{quote}
       
    99 
       
   100 \noindent
       
   101 Also IntelliJ includes plugins for Scala. \textbf{BUT}, I do not
       
   102 recommend the usage of Eclipse or IntelliJ for PEP: these IDEs seem to
       
   103 make your life harder, rather than easier, for the small programs we
       
   104 will write in this module. They are really meant to be used when you
       
   105 have a million-lines codebase, rather than our ``toy-programs''\ldots{}why 
       
   106 on earth am I required to create a completely new project with
       
   107 several subdirectories when I just want to try out 20-lines of Scala
       
   108 code? ;o)
    71 
   109 
    72 \subsection*{The Very Basics}
   110 \subsection*{The Very Basics}
    73 
   111 
    74 One advantage of Scala over Java is that it includes an interpreter (a
   112 One advantage of Scala over Java is that it includes an interpreter (a
    75 REPL, or
   113 REPL, or
    76 \underline{R}ead-\underline{E}val-\underline{P}rint-\underline{L}oop)
   114 \underline{R}ead-\underline{E}val-\underline{P}rint-\underline{L}oop)
    77 with which you can run and test small code-snippets without the need
   115 with which you can run and test small code snippets without the need
    78 of a compiler. This helps a lot with interactively developing
   116 of a compiler. This helps a lot with interactively developing
    79 programs. This is really the preferred way of writing small Scala
   117 programs. This is really my preferred way of writing small Scala
    80 programs. Once you installed Scala, you can start the interpreter by
   118 programs. Once you installed Scala, you can start the interpreter by
    81 typing on the command line:
   119 typing on the command line:
    82 
   120 
    83 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   121 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
    84 $ scala
   122 $ scala
    85 Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 9).
   123 Welcome to Scala 2.12.6 (Java HotSpot(TM) 64-Bit Server VM, Java 9).
    86 Type in expressions for evaluation. Or try :help.
   124 Type in expressions for evaluation. Or try :help.
    87 
   125 
    88 scala>
   126 scala>
    89 \end{lstlisting}%$
   127 \end{lstlisting}%$
    90 
   128 
    99 \end{lstlisting}
   137 \end{lstlisting}
   100 
   138 
   101 \noindent indicating that the result of the addition is of type
   139 \noindent indicating that the result of the addition is of type
   102 \code{Int} and the actual result is 5; \code{res0} is a name that
   140 \code{Int} and the actual result is 5; \code{res0} is a name that
   103 Scala gives automatically to the result. You can reuse this name later
   141 Scala gives automatically to the result. You can reuse this name later
   104 on. Another classic example you can try out is
   142 on. 
       
   143 
       
   144 \begin{lstlisting}[numbers=none]
       
   145 scala> res0 + 4
       
   146 res1: Int = 9
       
   147 \end{lstlisting}
       
   148 
       
   149 \noindent
       
   150 Another classic example you can try out is
   105 
   151 
   106 \begin{lstlisting}[numbers=none]
   152 \begin{lstlisting}[numbers=none]
   107 scala> print("hello world")
   153 scala> print("hello world")
   108 hello world
   154 hello world
   109 \end{lstlisting}
   155 \end{lstlisting}
   118 function that causes a side-effect, like \code{print}. We
   164 function that causes a side-effect, like \code{print}. We
   119 shall come back to this point later, but if you are curious
   165 shall come back to this point later, but if you are curious
   120 now, the latter kind of functions always has \code{Unit} as
   166 now, the latter kind of functions always has \code{Unit} as
   121 return type. It is just not printed.
   167 return type. It is just not printed.
   122 
   168 
   123 You can try more examples with the Scala interpreter, but try
   169 You can try more examples with the Scala REPL, but feel free to
   124 first to guess what the result is (not all answers by Scala are obvious):
   170 first guess what the result is (not all answers by Scala are obvious):
   125 
   171 
   126 \begin{lstlisting}[numbers=none]
   172 \begin{lstlisting}[numbers=none]
   127 scala> 2 + 2
   173 scala> 2 + 2
   128 scala> 1 / 2
   174 scala> 1 / 2
   129 scala> 1.0 / 2
   175 scala> 1.0 / 2
   132 scala> 1.0 / 0.0
   178 scala> 1.0 / 0.0
   133 scala> true == false
   179 scala> true == false
   134 scala> true && false
   180 scala> true && false
   135 scala> 1 > 1.0
   181 scala> 1 > 1.0
   136 scala> "12345".length
   182 scala> "12345".length
   137 \end{lstlisting}
   183 scala> List(1,2,1).size
   138 
   184 scala> Set(1,2,1).size
   139 \subsection*{Stand-Alone Scala Apps}
   185 \end{lstlisting}\smallskip
       
   186 
       
   187 \noindent
       
   188 Please take the Scala REPL seriously: If you want to take advantage of my
       
   189 reference implementation for the assignments, you will need to be
       
   190 able to ``play around'' with it!
       
   191 
       
   192 \subsection*{Standalone Scala Apps}
   140 
   193 
   141 If you want to write a stand-alone app in Scala, you can
   194 If you want to write a stand-alone app in Scala, you can
   142 implement an object that is an instance of \code{App}, say
   195 implement an object that is an instance of \code{App}, say
   143 
   196 
   144 \begin{lstlisting}[numbers=none]
   197 \begin{lstlisting}[numbers=none]
   146     println("hello world")
   199     println("hello world")
   147 }
   200 }
   148 \end{lstlisting}
   201 \end{lstlisting}
   149 
   202 
   150 \noindent save it in a file, for example {\tt hello-world.scala}, and
   203 \noindent save it in a file, for example {\tt hello-world.scala}, and
   151 then run the compiler and runtime environment:
   204 then run the compiler (\texttt{scalac}) and followed by the runtime
       
   205 environment (\texttt{scala}):
   152 
   206 
   153 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   207 \begin{lstlisting}[language={},numbers=none,basicstyle=\ttfamily\small]
   154 $ scalac hello-world.scala
   208 $ scalac hello-world.scala
   155 $ scala Hello
   209 $ scala Hello
   156 hello world
   210 hello world
   189 scala> val z = x / y
   243 scala> val z = x / y
   190 z: Int = 6
   244 z: Int = 6
   191 \end{lstlisting}
   245 \end{lstlisting}
   192 
   246 
   193 \noindent
   247 \noindent
   194 Why the kerfuffle about values? Well, values are \emph{immutable}. You cannot
   248 Why the kerfuffle about values? Well, values are \emph{immutable}. You 
   195 change their value after you defined them. If you try to reassign
   249 cannot change their value after you defined them. If you try to reassign
   196 \code{z} above, Scala will yell at you:
   250 \code{z} above, Scala will yell at you:
   197 
   251 
   198 \begin{lstlisting}[numbers=none]
   252 \begin{lstlisting}[numbers=none]
   199 scala> z = 9
   253 scala> z = 9
   200 error: reassignment to val
   254 error: reassignment to val
   202          ^
   256          ^
   203 \end{lstlisting}
   257 \end{lstlisting}
   204 
   258 
   205 \noindent
   259 \noindent
   206 So it would be a bit absurd to call values as variables...you cannot
   260 So it would be a bit absurd to call values as variables...you cannot
   207 change them. You might think you can re-assign them like
   261 change them; they cannot vary. You might think you can re-assign them like
   208 
   262 
   209 \begin{lstlisting}[numbers=none]
   263 \begin{lstlisting}[numbers=none]
   210 scala> val x = 42
   264 scala> val x = 42
   211 scala> val z = x / 7
   265 scala> val z = x / 7
   212 scala> val x = 70
   266 scala> val x = 70
   219 lower case, like \code{x}, \code{y}, \code{foo41} and so on.
   273 lower case, like \code{x}, \code{y}, \code{foo41} and so on.
   220 
   274 
   221 
   275 
   222 \subsection*{Function Definitions}
   276 \subsection*{Function Definitions}
   223 
   277 
   224 We do functional programming. So defining functions will be our main occupation.
   278 We do functional programming! So defining functions will be our main occupation.
   225 A function \code{f} taking a single argument of type \code{Int} can be defined in Scala
   279 A function named, lets say, \code{f} taking a single argument of type 
   226 as follows:
   280 \code{Int} can be defined in Scala as follows:
   227 
   281 
   228 \begin{lstlisting}[numbers=none]
   282 \begin{lstlisting}[numbers=none]
   229 def f(x: Int) : String = EXPR
   283 def f(x: Int) : String = ...EXPR...
   230 \end{lstlisting} 
   284 \end{lstlisting} 
   231 
   285 
   232 \noindent
   286 \noindent
   233 This function returns the value resulting from evaluating the expression
   287 This function returns the value resulting from evaluating the expression
   234 \code{EXPR} (whatever is substituted for this). The result will be
   288 \code{EXPR} (whatever is substituted for this). The result will be
   235 of type \code{String}. It is a good habbit to include this information
   289 of type \code{String}. It is a good habit to include this information
   236 about the return type always. Simple examples of Scala functions are:
   290 about the return type always. Simple examples of Scala functions are:
   237 
   291 
   238 \begin{lstlisting}[numbers=none]
   292 \begin{lstlisting}[numbers=none]
   239 def incr(x: Int) : Int = x + 1
   293 def incr(x: Int) : Int = x + 1
   240 def double(x: Int) : Int = x + x
   294 def double(x: Int) : Int = x + x
   625 requires that the generic traversal functions can cope with
   679 requires that the generic traversal functions can cope with
   626 any kind of function (not just functions that, for example,
   680 any kind of function (not just functions that, for example,
   627 take as input an integer and produce a string like above).
   681 take as input an integer and produce a string like above).
   628 This means we cannot fix the type of the generic traversal
   682 This means we cannot fix the type of the generic traversal
   629 functions, but have to keep them
   683 functions, but have to keep them
   630 \emph{polymorphic}.\footnote{Another interestic topic about
   684 \emph{polymorphic}.\footnote{Another interesting topic about
   631 types, but we omit it here for the sake of brevity.} 
   685 types, but we omit it here for the sake of brevity.} 
   632 
   686 
   633 There is one more type constructor that is rather special. It
   687 There is one more type constructor that is rather special. It
   634 is called \code{Unit}. Recall that \code{Boolean} has two
   688 is called \code{Unit}. Recall that \code{Boolean} has two
   635 values, namely \code{true} and \code{false}. This can be used,
   689 values, namely \code{true} and \code{false}. This can be used,
   826 % expressions from the inductive datatype.
   880 % expressions from the inductive datatype.
   827 
   881 
   828 \bigskip\noindent
   882 \bigskip\noindent
   829 \textit{More TBD.}
   883 \textit{More TBD.}
   830 
   884 
       
   885 \subsection*{Coursework}
       
   886 
   831 \subsection*{More Info}
   887 \subsection*{More Info}
   832 
   888 
   833 There is much more to Scala than I can possibly describe in
   889 There is much more to Scala than I can possibly describe in
   834 this document. Fortunately there are a number of free books
   890 this document. Fortunately there are a number of free books
   835 about Scala and of course lots of help online. For example
   891 about Scala and of course lots of help online. For example