| 51 |      1 | // Scala Lecture 1
 | 
|  |      2 | //=================
 | 
| 14 |      3 | 
 | 
| 26 |      4 | // Value assignments
 | 
| 123 |      5 | // (their names should be lower case)
 | 
| 199 |      6 | //====================================
 | 
| 21 |      7 | 
 | 
| 14 |      8 | val x = 42
 | 
|  |      9 | val y = 3 + 4
 | 
| 123 |     10 | val z = x / y
 | 
|  |     11 | 
 | 
|  |     12 | 
 | 
|  |     13 | // (you cannot reassign values: z = 9 will give an error)
 | 
| 14 |     14 | 
 | 
|  |     15 | 
 | 
| 125 |     16 | // Hello World
 | 
|  |     17 | //=============
 | 
|  |     18 | 
 | 
| 199 |     19 | // an example of a stand-alone Scala file
 | 
|  |     20 | // (in the assignments you must submit a plain Scala script)
 | 
| 125 |     21 | 
 | 
|  |     22 | object Hello extends App { 
 | 
|  |     23 |   println("hello world")
 | 
|  |     24 | }
 | 
|  |     25 | 
 | 
| 199 |     26 | // can then be called with
 | 
| 125 |     27 | //
 | 
|  |     28 | // $> scalac hello-world.scala
 | 
|  |     29 | // $> scala Hello
 | 
|  |     30 | //
 | 
|  |     31 | // $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
 | 
|  |     32 | 
 | 
|  |     33 | 
 | 
|  |     34 | 
 | 
| 25 |     35 | // Collections
 | 
|  |     36 | //=============
 | 
| 14 |     37 | List(1,2,3,1)
 | 
|  |     38 | Set(1,2,3,1)
 | 
|  |     39 | 
 | 
|  |     40 | 1 to 10
 | 
|  |     41 | (1 to 10).toList
 | 
|  |     42 | 
 | 
|  |     43 | (1 until 10).toList
 | 
|  |     44 | 
 | 
| 18 |     45 | // an element in a list
 | 
| 33 |     46 | val lst = List(1, 2, 3, 1)
 | 
|  |     47 | lst(0)
 | 
|  |     48 | lst(2)
 | 
| 18 |     49 | 
 | 
| 34 |     50 | // some alterative syntax for lists
 | 
|  |     51 | 
 | 
| 189 |     52 | 1 :: 2 :: 3 :: Nil
 | 
| 23 |     53 | List(1, 2, 3) ::: List(4, 5, 6)
 | 
| 14 |     54 | 
 | 
| 199 |     55 | // Equality is structural
 | 
|  |     56 | //========================
 | 
|  |     57 | val a = "Dave"
 | 
|  |     58 | val b = "Dave"
 | 
|  |     59 | 
 | 
|  |     60 | if (a == b) println("equal") else println("unequal")
 | 
|  |     61 | 
 | 
|  |     62 | Set(1,2,3) == Set(3,1,2)
 | 
|  |     63 | List(1,2,3) == List(3,1,2)
 | 
|  |     64 | 
 | 
|  |     65 | 
 | 
|  |     66 | // this applies for "concrete" values;
 | 
|  |     67 | // you cannot compare functions
 | 
|  |     68 | 
 | 
|  |     69 | 
 | 
| 25 |     70 | // Printing/Strings
 | 
|  |     71 | //==================
 | 
| 14 |     72 | 
 | 
|  |     73 | println("test")
 | 
| 15 |     74 | 
 | 
| 33 |     75 | val tst = "This is a " + "test\n" 
 | 
| 14 |     76 | println(tst)
 | 
|  |     77 | 
 | 
|  |     78 | val lst = List(1,2,3,1)
 | 
|  |     79 | 
 | 
|  |     80 | println(lst.toString)
 | 
|  |     81 | println(lst.mkString("\n"))
 | 
|  |     82 | 
 | 
| 33 |     83 | println(lst.mkString(", "))
 | 
|  |     84 | 
 | 
| 14 |     85 | // some methods take more than one argument
 | 
| 21 |     86 | println(lst.mkString("[", ",", "]"))
 | 
| 14 |     87 | 
 | 
| 32 |     88 | 
 | 
| 25 |     89 | // Conversion methods
 | 
|  |     90 | //====================
 | 
| 14 |     91 | 
 | 
|  |     92 | List(1,2,3,1).toString
 | 
|  |     93 | List(1,2,3,1).toSet
 | 
|  |     94 | "hello".toList
 | 
|  |     95 | 1.toDouble
 | 
|  |     96 | 
 | 
| 25 |     97 | 
 | 
| 32 |     98 | // useful list methods
 | 
|  |     99 | 
 | 
|  |    100 | List(1,2,3,4).length
 | 
| 25 |    101 | List(1,2,3,4).reverse
 | 
| 32 |    102 | List(1,2,3,4).max
 | 
|  |    103 | List(1,2,3,4).min
 | 
|  |    104 | List(1,2,3,4).sum
 | 
|  |    105 | List(1,2,3,4).take(2).sum
 | 
|  |    106 | List(1,2,3,4).drop(2).sum
 | 
| 199 |    107 | List(1,2,3,4,3).indexOf(3)
 | 
| 32 |    108 | 
 | 
| 36 |    109 | "1,2,3,4,5".split(",").mkString("\n")
 | 
|  |    110 | "1,2,3,4,5".split(",3,").mkString("\n")
 | 
| 25 |    111 | 
 | 
| 140 |    112 | // Types (slide)
 | 
| 25 |    113 | //=======
 | 
|  |    114 | 
 | 
|  |    115 | /* Scala is a strongly typed language
 | 
|  |    116 |  
 | 
| 34 |    117 |  * some base types
 | 
| 14 |    118 | 
 | 
| 25 |    119 |     Int, Long, BigInt, Float, Double
 | 
|  |    120 |     String, Char
 | 
|  |    121 |     Boolean
 | 
|  |    122 | 
 | 
| 34 |    123 |  * some compound types 
 | 
| 12 |    124 | 
 | 
| 25 |    125 |     List[Int],
 | 
|  |    126 |     Set[Double]
 | 
|  |    127 |     Pairs: (Int, String)        
 | 
|  |    128 |     List[(BigInt, String)]
 | 
|  |    129 | */
 | 
| 12 |    130 | 
 | 
| 23 |    131 | 
 | 
| 14 |    132 | 
 | 
| 25 |    133 | // Pairs/Tuples
 | 
|  |    134 | //==============
 | 
| 14 |    135 | 
 | 
|  |    136 | val p = (1, "one")
 | 
|  |    137 | p._1
 | 
|  |    138 | p._2
 | 
|  |    139 | 
 | 
|  |    140 | val t = (4,1,2,3)
 | 
|  |    141 | t._4
 | 
|  |    142 | 
 | 
| 25 |    143 | 
 | 
|  |    144 | // Function Definitions
 | 
|  |    145 | //======================
 | 
| 14 |    146 | 
 | 
| 123 |    147 | def incr(x: Int) : Int = x + 1
 | 
|  |    148 | def double(x: Int) : Int = x + x
 | 
|  |    149 | def square(x: Int) : Int = x * x
 | 
| 14 |    150 | 
 | 
| 25 |    151 | square(6)
 | 
| 21 |    152 | 
 | 
|  |    153 | 
 | 
| 36 |    154 | // The general scheme for a function: you have to give a type 
 | 
|  |    155 | // to each argument and a return type of the function
 | 
|  |    156 | //
 | 
|  |    157 | //  def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
 | 
|  |    158 | //    body 
 | 
|  |    159 | //  }
 | 
|  |    160 | 
 | 
|  |    161 | 
 | 
|  |    162 | 
 | 
| 123 |    163 | // If-Conditionals
 | 
|  |    164 | //=================
 | 
| 14 |    165 | 
 | 
| 189 |    166 | // Scala does not have a then-keyword
 | 
| 199 |    167 | // both if-else branches need to be present
 | 
| 189 |    168 | 
 | 
| 143 |    169 | def fact(n: Int) : Int = 
 | 
| 14 |    170 |   if (n == 0) 1 else n * fact(n - 1)
 | 
|  |    171 | 
 | 
| 36 |    172 | 
 | 
|  |    173 | fact(5)
 | 
|  |    174 | fact(150)
 | 
|  |    175 | 
 | 
| 25 |    176 | /* boolean operators
 | 
|  |    177 |  
 | 
|  |    178 |    ==     equals
 | 
|  |    179 |    !      not
 | 
|  |    180 |    && ||  and, or
 | 
|  |    181 | */
 | 
| 15 |    182 | 
 | 
|  |    183 | 
 | 
| 189 |    184 | def fact2(n: BigInt) : BigInt = 
 | 
| 14 |    185 |   if (n == 0) 1 else n * fact2(n - 1)
 | 
|  |    186 | 
 | 
| 25 |    187 | fact2(150)
 | 
|  |    188 | 
 | 
| 26 |    189 | 
 | 
| 189 |    190 | def fib(n: Int) : Int =
 | 
| 14 |    191 |   if (n == 0) 1 else
 | 
| 26 |    192 |     if (n == 1) 1 else fib(n - 1) + fib(n - 2)
 | 
| 14 |    193 | 
 | 
|  |    194 | 
 | 
| 26 |    195 | //gcd - Euclid's algorithm
 | 
|  |    196 | 
 | 
| 123 |    197 | def gcd(a: Int, b: Int) : Int =
 | 
| 26 |    198 |   if (b == 0) a else gcd(b, a % b)
 | 
|  |    199 | 
 | 
|  |    200 | gcd(48, 18)
 | 
|  |    201 | 
 | 
| 14 |    202 | 
 | 
| 123 |    203 | def power(x: Int, n: Int) : Int =
 | 
| 199 |    204 |   if (n == 0) 1 else x * power(x, n - 1) 
 | 
| 123 |    205 | 
 | 
|  |    206 | power(5, 5)
 | 
|  |    207 | 
 | 
|  |    208 | 
 | 
| 199 |    209 | // Option type
 | 
|  |    210 | //=============
 | 
|  |    211 | 
 | 
|  |    212 | //in Java if something unusually happens, you return null
 | 
|  |    213 | //
 | 
|  |    214 | //in Scala you use Option
 | 
|  |    215 | //   - if the value is present, you use Some(value)
 | 
|  |    216 | //   - if no value is present, you use None
 | 
|  |    217 | 
 | 
|  |    218 | 
 | 
|  |    219 | List(7,2,3,4,5,6).find(_ < 4)
 | 
|  |    220 | List(5,6,7,8,9).find(_ < 4)
 | 
|  |    221 | 
 | 
|  |    222 | 
 | 
|  |    223 | 
 | 
|  |    224 | // error handling with Options (no exceptions)
 | 
|  |    225 | //
 | 
|  |    226 | //  Try(something).getOrElse(what_to_do_in_case_of_an_exception)
 | 
|  |    227 | //
 | 
|  |    228 | import scala.util._
 | 
|  |    229 | import io.Source
 | 
|  |    230 | 
 | 
|  |    231 | val my_url = "https://nms.kcl.ac.uk/christian.urban/"
 | 
|  |    232 | 
 | 
|  |    233 | Source.fromURL(my_url).mkString
 | 
|  |    234 | 
 | 
|  |    235 | Try(Source.fromURL(my_url).mkString).getOrElse("")
 | 
|  |    236 | 
 | 
|  |    237 | Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
 | 
|  |    238 | 
 | 
|  |    239 | 
 | 
|  |    240 | // the same for files
 | 
|  |    241 | Source.fromFile("test.txt").mkString
 | 
|  |    242 | 
 | 
|  |    243 | 
 | 
| 25 |    244 | // String Interpolations
 | 
|  |    245 | //=======================
 | 
| 14 |    246 | 
 | 
| 26 |    247 | val n = 3
 | 
|  |    248 | println("The square of " + n + " is " + square(n) + ".")
 | 
|  |    249 | 
 | 
|  |    250 | println(s"The square of ${n} is ${square(n)}.")
 | 
|  |    251 | 
 | 
|  |    252 | 
 | 
|  |    253 | 
 | 
| 123 |    254 | def gcd_db(a: Int, b: Int) : Int = {
 | 
| 26 |    255 |   println(s"Function called with ${a} and ${b}.")
 | 
|  |    256 |   if (b == 0) a else gcd_db(b, a % b)
 | 
|  |    257 | }
 | 
|  |    258 | 
 | 
|  |    259 | gcd_db(48, 18)
 | 
|  |    260 | 
 | 
| 14 |    261 | 
 | 
| 124 |    262 | // Asserts/Testing
 | 
| 25 |    263 | //================
 | 
| 14 |    264 | 
 | 
| 32 |    265 | assert(gcd(48, 18) == 6)
 | 
|  |    266 | 
 | 
|  |    267 | assert(gcd(48, 18) == 5, "The gcd test failed")
 | 
|  |    268 | 
 | 
|  |    269 | 
 | 
| 26 |    270 | // For-Comprehensions (not For-Loops)
 | 
|  |    271 | //====================================
 | 
| 14 |    272 | 
 | 
|  |    273 | for (n <- (1 to 10).toList) yield square(n)
 | 
|  |    274 | 
 | 
| 25 |    275 | for (n <- (1 to 10).toList; 
 | 
|  |    276 |      m <- (1 to 10).toList) yield m * n
 | 
| 21 |    277 | 
 | 
|  |    278 | 
 | 
| 26 |    279 | val mult_table = 
 | 
|  |    280 |   for (n <- (1 to 10).toList; 
 | 
|  |    281 |        m <- (1 to 10).toList) yield m * n
 | 
|  |    282 | 
 | 
|  |    283 | mult_table.sliding(10,10).mkString("\n")
 | 
|  |    284 | 
 | 
| 189 |    285 | // the list can also be constructed in any other way
 | 
|  |    286 | for (n <- List(10,12,4,5,7,8,10)) yield n * n
 | 
|  |    287 | 
 | 
| 25 |    288 | 
 | 
| 32 |    289 | // with if-predicates
 | 
|  |    290 | 
 | 
|  |    291 | for (n <- (1 to 3).toList; 
 | 
|  |    292 |      m <- (1 to 3).toList;
 | 
|  |    293 |      if (n + m) % 2 == 0) yield (n, m)
 | 
|  |    294 | 
 | 
| 148 |    295 | for (n <- (1 to 3).toList; 
 | 
|  |    296 |      m <- (1 to 3).toList;
 | 
|  |    297 |      if ((n + m) % 2 == 0)) yield (n, m)
 | 
| 32 |    298 | 
 | 
| 26 |    299 | // with patterns
 | 
|  |    300 | 
 | 
| 199 |    301 | val lst = List((1, 4), (2, 3), (3, 2), (4, 1))
 | 
| 26 |    302 | 
 | 
| 199 |    303 | for ((m, n) <- lst) yield m + n 
 | 
|  |    304 | 
 | 
|  |    305 | for (p <- lst) yield p._1 + p._2 
 | 
| 26 |    306 | 
 | 
| 25 |    307 | 
 | 
| 189 |    308 | // general pattern
 | 
|  |    309 | 
 | 
|  |    310 | for (x <- ...) yield {
 | 
|  |    311 |   // potentially complicated
 | 
|  |    312 |   // calculation of a result
 | 
|  |    313 | }
 | 
|  |    314 | 
 | 
|  |    315 | 
 | 
| 25 |    316 | 
 | 
| 36 |    317 | // with only a side-effect (no list is produced),
 | 
| 32 |    318 | // has no "yield"
 | 
|  |    319 | 
 | 
|  |    320 | for (n <- (1 to 10)) println(n)
 | 
|  |    321 | 
 | 
|  |    322 | 
 | 
| 199 |    323 | // BTW: a roundabout way of printing out a list, say
 | 
|  |    324 | val lst = ('a' to 'm').toList
 | 
| 140 |    325 | 
 | 
| 199 |    326 | for (i <- (0 until lst.length)) println(lst(i))
 | 
|  |    327 | 
 | 
|  |    328 | // why not?
 | 
|  |    329 | for (c <- lst) println(c)
 | 
|  |    330 | 
 | 
|  |    331 | // Aside: concurrency 
 | 
|  |    332 | // (ONLY WORKS OUT-OF-THE-BOX IN SCALA 2.11.8, not in SCALA 2.12)
 | 
|  |    333 | // (would need to have this wrapped into a function, or
 | 
|  |    334 | //  REPL called with scala -Yrepl-class-based)
 | 
| 32 |    335 | for (n <- (1 to 10)) println(n)
 | 
|  |    336 | for (n <- (1 to 10).par) println(n)
 | 
|  |    337 | 
 | 
|  |    338 | 
 | 
| 36 |    339 | // for measuring time
 | 
| 140 |    340 | def time_needed[T](n: Int, code: => T) = {
 | 
| 32 |    341 |   val start = System.nanoTime()
 | 
| 140 |    342 |   for (i <- (0 to n)) code
 | 
| 32 |    343 |   val end = System.nanoTime()
 | 
| 140 |    344 |   (end - start) / 1.0e9
 | 
| 32 |    345 | }
 | 
|  |    346 | 
 | 
| 140 |    347 | 
 | 
| 32 |    348 | val list = (1 to 1000000).toList
 | 
|  |    349 | time_needed(10, for (n <- list) yield n + 42)
 | 
|  |    350 | time_needed(10, for (n <- list.par) yield n + 42)
 | 
|  |    351 | 
 | 
|  |    352 | 
 | 
| 199 |    353 | // Function producing multiple outputs
 | 
|  |    354 | //=====================================
 | 
| 140 |    355 | 
 | 
| 199 |    356 | def get_ascii(c: Char) : (Char, Int) = (c, c.toInt)
 | 
| 140 |    357 | 
 | 
| 199 |    358 | get_ascii('a')
 | 
| 137 |    359 | 
 | 
|  |    360 | 
 | 
| 32 |    361 | 
 | 
| 199 |    362 | // .maxBy, sortBy with pairs
 | 
|  |    363 | def get_length(s: String) : (String, Int) = (s, s.length) 
 | 
| 32 |    364 | 
 | 
| 199 |    365 | val lst = List("zero", "one", "two", "three", "four", "ten")
 | 
|  |    366 | val strs = for (s <- lst) yield get_length(s)
 | 
| 32 |    367 | 
 | 
| 199 |    368 | strs.sortBy(_._2)
 | 
|  |    369 | strs.sortBy(_._1)
 | 
| 32 |    370 | 
 | 
| 199 |    371 | strs.maxBy(_._2)
 | 
|  |    372 | strs.maxBy(_._1)
 | 
| 32 |    373 | 
 | 
|  |    374 | // Further Information
 | 
|  |    375 | //=====================
 | 
|  |    376 | 
 | 
| 123 |    377 | // The Scala home page and general information is at
 | 
| 32 |    378 | //
 | 
|  |    379 | //  http://www.scala-lang.org
 | 
| 123 |    380 | //	http://docs.scala-lang.org
 | 
|  |    381 | //
 | 
|  |    382 | //
 | 
|  |    383 | // It should be fairly easy to install the Scala binary and
 | 
|  |    384 | // run Scala on the commandline. There are also at least 
 | 
|  |    385 | // four IDEs you can use with Scala:
 | 
|  |    386 | //
 | 
| 124 |    387 | //  (0) Some general information about setting up IDEs
 | 
| 123 |    388 | //	    with Scala support can be found at
 | 
|  |    389 | //
 | 
|  |    390 | //         http://docs.scala-lang.org/getting-started.html 
 | 
|  |    391 | //
 | 
| 124 |    392 | //
 | 
| 123 |    393 | //  (1) Eclipse for Scala (one big bundle)
 | 
|  |    394 | //
 | 
|  |    395 | //         http://scala-ide.org/download/sdk.html
 | 
|  |    396 | //  
 | 
|  |    397 | //  (2) IntelliJ (needs additional Plugins)
 | 
|  |    398 | //
 | 
|  |    399 | //         https://www.jetbrains.com/idea/
 | 
|  |    400 | //		   http://docs.scala-lang.org/getting-started-intellij-track/getting-started-with-scala-in-intellij.html	  
 | 
|  |    401 | //
 | 
|  |    402 | //  (3) Sublime (not free, but unlimited trial period; 
 | 
| 124 |    403 | //	    needs Scala and SublimeREPL plugin)
 | 
| 123 |    404 | //
 | 
|  |    405 | //         https://www.sublimetext.com
 | 
|  |    406 | //
 | 
|  |    407 | //  (4) Emacs (old-fashioned, but reliable)
 | 
|  |    408 | //
 | 
|  |    409 | //         https://www.gnu.org/software/emacs/
 | 
| 32 |    410 | //
 | 
| 123 |    411 | //      I use the old scala-tool support for Emacs distributed at
 | 
|  |    412 | //
 | 
|  |    413 | //         https://github.com/scala/scala-tool-support/tree/master/tool-support/emacs 
 | 
|  |    414 | //
 | 
|  |    415 | //      but there is also support for the newer Ensime Scala Mode
 | 
|  |    416 | //
 | 
|  |    417 | //         http://ensime.org/editors/emacs/scala-mode/   
 | 
|  |    418 | //   
 | 
|  |    419 | // There is also Scala support in the Atom editor, but my
 | 
|  |    420 | // experience is mixed. People also use Scala with Vim and Jedit.
 | 
| 124 |    421 | // Finally there is an online editor specifically designed for 
 | 
|  |    422 | // running Scala applications (but do not blame mne if you lose all 
 | 
|  |    423 | // what you typed in):
 | 
|  |    424 | //
 | 
|  |    425 | //      https://scalafiddle.io 
 | 
|  |    426 | //
 | 
|  |    427 | //
 | 
| 123 |    428 | //
 | 
|  |    429 | // All of the IDEs above support a REPL for Scala. Some of them have
 | 
|  |    430 | // the very nifty feature of a Scala Worksheet -- you just save your
 | 
|  |    431 | // file and it will be automatically evaluated and the result pasted
 | 
|  |    432 | // into your file. However, this way of writing Scala code never worked
 | 
|  |    433 | // for me. I just use the REPL.
 | 
|  |    434 | //
 | 
|  |    435 | //
 | 
|  |    436 | // Scala Library Docs
 | 
| 124 |    437 | //====================
 | 
| 123 |    438 | //
 | 
|  |    439 | //  http://www.scala-lang.org/api/current/
 | 
|  |    440 | //
 | 
|  |    441 | // Scala Tutorials
 | 
|  |    442 | //
 | 
|  |    443 | //  http://docs.scala-lang.org/tutorials/
 | 
|  |    444 | //
 | 
|  |    445 | // There are also a massive number of Scala tutorials on youtube
 | 
|  |    446 | // and there are tons of books and free material.
 | 
|  |    447 | //
 | 
| 32 |    448 | 
 | 
|  |    449 | 
 | 
| 170 |    450 | 
 | 
|  |    451 | 
 | 
|  |    452 | 
 | 
|  |    453 | 
 | 
|  |    454 | 
 | 
|  |    455 | 
 | 
|  |    456 | 
 | 
| 195 |    457 | 
 | 
|  |    458 | 
 | 
|  |    459 | 
 | 
|  |    460 | 
 | 
|  |    461 | 
 | 
|  |    462 | 
 |