| 51 |      1 | // Scala Lecture 1
 | 
|  |      2 | //=================
 | 
| 14 |      3 | 
 | 
| 26 |      4 | // Value assignments
 | 
| 123 |      5 | // (their names should be lower case)
 | 
|  |      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 | 
 | 
|  |     17 | // Hello World
 | 
|  |     18 | //=============
 | 
|  |     19 | 
 | 
|  |     20 | // an example of a stand-alone scala file;
 | 
|  |     21 | // in the coursework students must submit 
 | 
|  |     22 | // plain scala "work-sheets"
 | 
|  |     23 | 
 | 
|  |     24 | object Hello extends App { 
 | 
|  |     25 |   println("hello world")
 | 
|  |     26 | }
 | 
|  |     27 | 
 | 
|  |     28 | // can be called with
 | 
|  |     29 | //
 | 
|  |     30 | // $> scalac hello-world.scala
 | 
|  |     31 | // $> scala Hello
 | 
|  |     32 | //
 | 
|  |     33 | // $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
 | 
|  |     34 | 
 | 
|  |     35 | 
 | 
|  |     36 | 
 | 
|  |     37 | 
 | 
| 25 |     38 | // Collections
 | 
|  |     39 | //=============
 | 
| 14 |     40 | List(1,2,3,1)
 | 
|  |     41 | Set(1,2,3,1)
 | 
|  |     42 | 
 | 
|  |     43 | 1 to 10
 | 
|  |     44 | (1 to 10).toList
 | 
|  |     45 | 
 | 
|  |     46 | (1 until 10).toList
 | 
|  |     47 | 
 | 
| 18 |     48 | // an element in a list
 | 
| 33 |     49 | val lst = List(1, 2, 3, 1)
 | 
|  |     50 | lst(0)
 | 
|  |     51 | lst(2)
 | 
| 18 |     52 | 
 | 
| 34 |     53 | // some alterative syntax for lists
 | 
|  |     54 | 
 | 
| 23 |     55 | 1::2::3::Nil
 | 
|  |     56 | List(1, 2, 3) ::: List(4, 5, 6)
 | 
| 14 |     57 | 
 | 
| 25 |     58 | // Printing/Strings
 | 
|  |     59 | //==================
 | 
| 14 |     60 | 
 | 
|  |     61 | println("test")
 | 
| 15 |     62 | 
 | 
| 33 |     63 | val tst = "This is a " + "test\n" 
 | 
| 14 |     64 | println(tst)
 | 
|  |     65 | 
 | 
|  |     66 | val lst = List(1,2,3,1)
 | 
|  |     67 | 
 | 
|  |     68 | println(lst.toString)
 | 
|  |     69 | println(lst.mkString("\n"))
 | 
|  |     70 | 
 | 
| 33 |     71 | println(lst.mkString(", "))
 | 
|  |     72 | 
 | 
| 14 |     73 | // some methods take more than one argument
 | 
| 21 |     74 | println(lst.mkString("[", ",", "]"))
 | 
| 14 |     75 | 
 | 
| 32 |     76 | 
 | 
| 25 |     77 | // Conversion methods
 | 
|  |     78 | //====================
 | 
| 14 |     79 | 
 | 
|  |     80 | List(1,2,3,1).toString
 | 
|  |     81 | List(1,2,3,1).toSet
 | 
|  |     82 | "hello".toList
 | 
|  |     83 | 1.toDouble
 | 
|  |     84 | 
 | 
| 25 |     85 | 
 | 
| 32 |     86 | // useful list methods
 | 
|  |     87 | 
 | 
|  |     88 | List(1,2,3,4).length
 | 
| 25 |     89 | List(1,2,3,4).reverse
 | 
| 32 |     90 | List(1,2,3,4).max
 | 
|  |     91 | List(1,2,3,4).min
 | 
|  |     92 | List(1,2,3,4).sum
 | 
|  |     93 | List(1,2,3,4).take(2).sum
 | 
|  |     94 | List(1,2,3,4).drop(2).sum
 | 
| 123 |     95 | List(1,2,3,4,3)indexOf(3)
 | 
| 32 |     96 | 
 | 
| 36 |     97 | "1,2,3,4,5".split(",").mkString("\n")
 | 
|  |     98 | "1,2,3,4,5".split(",3,").mkString("\n")
 | 
| 25 |     99 | 
 | 
|  |    100 | // Types
 | 
|  |    101 | //=======
 | 
|  |    102 | 
 | 
|  |    103 | /* Scala is a strongly typed language
 | 
|  |    104 |  
 | 
| 34 |    105 |  * some base types
 | 
| 14 |    106 | 
 | 
| 25 |    107 |     Int, Long, BigInt, Float, Double
 | 
|  |    108 |     String, Char
 | 
|  |    109 |     Boolean
 | 
|  |    110 | 
 | 
| 34 |    111 |  * some compound types 
 | 
| 12 |    112 | 
 | 
| 25 |    113 |     List[Int],
 | 
|  |    114 |     Set[Double]
 | 
|  |    115 |     Pairs: (Int, String)        
 | 
|  |    116 |     List[(BigInt, String)]
 | 
|  |    117 | */
 | 
| 12 |    118 | 
 | 
| 25 |    119 | // Smart Strings
 | 
|  |    120 | //===============
 | 
|  |    121 | 
 | 
| 36 |    122 | println(">\n\n<")
 | 
| 23 |    123 | println(""">\n<""")
 | 
| 36 |    124 | println("""">\n<"""")
 | 
| 23 |    125 | 
 | 
|  |    126 | /* in Java
 | 
|  |    127 | val lyrics = "Baa, Baa, Black Sheep \n" +
 | 
|  |    128 |              "Have you any wool? \n" +
 | 
|  |    129 |              "Yes, sir, yes sir \n" +
 | 
|  |    130 |              "Three bags full"
 | 
|  |    131 | */ 
 | 
|  |    132 | 
 | 
|  |    133 | val lyrics = """Baa, Baa, Black Sheep  
 | 
|  |    134 |                 |Have you any wool?
 | 
|  |    135 |                 |Yes, sir, yes sir
 | 
|  |    136 |                 |Three bags full""".stripMargin
 | 
|  |    137 | 
 | 
|  |    138 | println(lyrics)
 | 
|  |    139 | 
 | 
| 14 |    140 | 
 | 
| 25 |    141 | // Pairs/Tuples
 | 
|  |    142 | //==============
 | 
| 14 |    143 | 
 | 
|  |    144 | val p = (1, "one")
 | 
|  |    145 | p._1
 | 
|  |    146 | p._2
 | 
|  |    147 | 
 | 
|  |    148 | val t = (4,1,2,3)
 | 
|  |    149 | t._4
 | 
|  |    150 | 
 | 
| 25 |    151 | 
 | 
|  |    152 | // Function Definitions
 | 
|  |    153 | //======================
 | 
| 14 |    154 | 
 | 
| 123 |    155 | def incr(x: Int) : Int = x + 1
 | 
|  |    156 | def double(x: Int) : Int = x + x
 | 
|  |    157 | def square(x: Int) : Int = x * x
 | 
| 14 |    158 | 
 | 
| 25 |    159 | square(6)
 | 
| 21 |    160 | 
 | 
|  |    161 | 
 | 
| 36 |    162 | 
 | 
|  |    163 | // The general scheme for a function: you have to give a type 
 | 
|  |    164 | // to each argument and a return type of the function
 | 
|  |    165 | //
 | 
|  |    166 | //  def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
 | 
|  |    167 | //    body 
 | 
|  |    168 | //  }
 | 
|  |    169 | 
 | 
|  |    170 | 
 | 
|  |    171 | 
 | 
| 123 |    172 | // If-Conditionals
 | 
|  |    173 | //=================
 | 
| 14 |    174 | 
 | 
|  |    175 | def fact(n: Int): Int = 
 | 
|  |    176 |   if (n == 0) 1 else n * fact(n - 1)
 | 
|  |    177 | 
 | 
| 36 |    178 | 
 | 
|  |    179 | fact(5)
 | 
|  |    180 | fact(150)
 | 
|  |    181 | 
 | 
| 25 |    182 | /* boolean operators
 | 
|  |    183 |  
 | 
|  |    184 |    ==     equals
 | 
|  |    185 |    !      not
 | 
|  |    186 |    && ||  and, or
 | 
|  |    187 | */
 | 
| 15 |    188 | 
 | 
|  |    189 | 
 | 
| 14 |    190 | def fact2(n: BigInt): BigInt = 
 | 
|  |    191 |   if (n == 0) 1 else n * fact2(n - 1)
 | 
|  |    192 | 
 | 
| 25 |    193 | fact2(150)
 | 
|  |    194 | 
 | 
| 26 |    195 | 
 | 
| 14 |    196 | def fib(n: Int): Int =
 | 
|  |    197 |   if (n == 0) 1 else
 | 
| 26 |    198 |     if (n == 1) 1 else fib(n - 1) + fib(n - 2)
 | 
| 14 |    199 | 
 | 
|  |    200 | 
 | 
| 26 |    201 | //gcd - Euclid's algorithm
 | 
|  |    202 | 
 | 
| 123 |    203 | def gcd(a: Int, b: Int) : Int =
 | 
| 26 |    204 |   if (b == 0) a else gcd(b, a % b)
 | 
|  |    205 | 
 | 
|  |    206 | gcd(48, 18)
 | 
|  |    207 | 
 | 
| 14 |    208 | 
 | 
| 123 |    209 | def power(x: Int, n: Int) : Int =
 | 
|  |    210 |   if (n == 0) 1  else x * power(x, n - 1) 
 | 
|  |    211 | 
 | 
|  |    212 | power(5, 5)
 | 
|  |    213 | 
 | 
|  |    214 | 
 | 
| 25 |    215 | // String Interpolations
 | 
|  |    216 | //=======================
 | 
| 14 |    217 | 
 | 
| 26 |    218 | val n = 3
 | 
|  |    219 | println("The square of " + n + " is " + square(n) + ".")
 | 
|  |    220 | 
 | 
|  |    221 | println(s"The square of ${n} is ${square(n)}.")
 | 
|  |    222 | 
 | 
|  |    223 | 
 | 
|  |    224 | 
 | 
| 123 |    225 | def gcd_db(a: Int, b: Int) : Int = {
 | 
| 26 |    226 |   println(s"Function called with ${a} and ${b}.")
 | 
|  |    227 |   if (b == 0) a else gcd_db(b, a % b)
 | 
|  |    228 | }
 | 
|  |    229 | 
 | 
|  |    230 | gcd_db(48, 18)
 | 
|  |    231 | 
 | 
| 14 |    232 | 
 | 
| 124 |    233 | // Asserts/Testing
 | 
| 25 |    234 | //================
 | 
| 14 |    235 | 
 | 
| 32 |    236 | assert(gcd(48, 18) == 6)
 | 
|  |    237 | 
 | 
|  |    238 | assert(gcd(48, 18) == 5, "The gcd test failed")
 | 
|  |    239 | 
 | 
|  |    240 | 
 | 
| 26 |    241 | // For-Comprehensions (not For-Loops)
 | 
|  |    242 | //====================================
 | 
| 14 |    243 | 
 | 
|  |    244 | for (n <- (1 to 10).toList) yield square(n)
 | 
|  |    245 | 
 | 
| 25 |    246 | for (n <- (1 to 10).toList; 
 | 
|  |    247 |      m <- (1 to 10).toList) yield m * n
 | 
| 21 |    248 | 
 | 
|  |    249 | 
 | 
| 26 |    250 | val mult_table = 
 | 
|  |    251 |   for (n <- (1 to 10).toList; 
 | 
|  |    252 |        m <- (1 to 10).toList) yield m * n
 | 
|  |    253 | 
 | 
|  |    254 | mult_table.sliding(10,10).mkString("\n")
 | 
|  |    255 | 
 | 
| 25 |    256 | 
 | 
| 32 |    257 | // with if-predicates
 | 
|  |    258 | 
 | 
|  |    259 | for (n <- (1 to 3).toList; 
 | 
|  |    260 |      m <- (1 to 3).toList;
 | 
|  |    261 |      if (n + m) % 2 == 0) yield (n, m)
 | 
|  |    262 | 
 | 
|  |    263 | 
 | 
|  |    264 | 
 | 
| 26 |    265 | // with patterns
 | 
|  |    266 | 
 | 
|  |    267 | for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n 
 | 
|  |    268 | 
 | 
|  |    269 | for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 
 | 
|  |    270 | 
 | 
| 25 |    271 | 
 | 
|  |    272 | 
 | 
| 36 |    273 | // with only a side-effect (no list is produced),
 | 
| 32 |    274 | // has no "yield"
 | 
|  |    275 | 
 | 
|  |    276 | for (n <- (1 to 10)) println(n)
 | 
|  |    277 | 
 | 
|  |    278 | 
 | 
| 36 |    279 | // concurrency (ONLY WORKS IN SCALA 2.11.8, not in SCALA 2.12.0)
 | 
| 32 |    280 | for (n <- (1 to 10)) println(n)
 | 
|  |    281 | for (n <- (1 to 10).par) println(n)
 | 
|  |    282 | 
 | 
|  |    283 | 
 | 
| 36 |    284 | // for measuring time
 | 
| 32 |    285 | def time_needed[T](i: Int, code: => T) = {
 | 
|  |    286 |   val start = System.nanoTime()
 | 
|  |    287 |   for (j <- 1 to i) code
 | 
|  |    288 |   val end = System.nanoTime()
 | 
|  |    289 |   ((end - start) / i / 1.0e9) + " secs"
 | 
|  |    290 | }
 | 
|  |    291 | 
 | 
|  |    292 | val list = (1 to 1000000).toList
 | 
|  |    293 | time_needed(10, for (n <- list) yield n + 42)
 | 
|  |    294 | time_needed(10, for (n <- list.par) yield n + 42)
 | 
|  |    295 | 
 | 
|  |    296 | 
 | 
|  |    297 | 
 | 
| 25 |    298 | // Webpages
 | 
|  |    299 | //==========
 | 
| 32 |    300 | 
 | 
|  |    301 | import io.Source
 | 
|  |    302 | 
 | 
| 36 |    303 | // obtaining a webpage
 | 
| 123 |    304 | val url = """https://nms.kcl.ac.uk/christian.urban/""" 
 | 
| 32 |    305 | Source.fromURL(url)("ISO-8859-1").mkString
 | 
|  |    306 | 
 | 
|  |    307 | 
 | 
| 36 |    308 | // function for looking up stockmarket data 
 | 
| 124 |    309 | def price_lookup(symbol: String) : String = {
 | 
| 123 |    310 |   val url = "https://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=snl1"
 | 
| 32 |    311 |   Source.fromURL(url).mkString.drop(1).dropRight(2)
 | 
|  |    312 | }
 | 
|  |    313 | 
 | 
|  |    314 | price_lookup("GOOG")
 | 
|  |    315 | price_lookup("AAPL")
 | 
|  |    316 | 
 | 
|  |    317 | 
 | 
|  |    318 | val companies = 
 | 
|  |    319 |   List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU")
 | 
|  |    320 | 
 | 
| 123 |    321 | for (s <- companies) println(price_lookup(s))
 | 
| 32 |    322 | 
 | 
|  |    323 | 
 | 
| 123 |    324 | // A Web Crawler 
 | 
| 32 |    325 | //===============
 | 
| 36 |    326 | //
 | 
| 123 |    327 | // the idea is to look for dead links using the
 | 
|  |    328 | // regular expression "https?://[^"]*"
 | 
| 32 |    329 | 
 | 
|  |    330 | import io.Source
 | 
|  |    331 | import scala.util.matching.Regex
 | 
|  |    332 | import scala.util._
 | 
|  |    333 | 
 | 
|  |    334 | // gets the first 10K of a web-page
 | 
|  |    335 | def get_page(url: String) : String = {
 | 
|  |    336 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | 
|  |    337 |     getOrElse { println(s"  Problem with: $url"); ""}
 | 
|  |    338 | }
 | 
|  |    339 | 
 | 
|  |    340 | // regex for URLs
 | 
|  |    341 | val http_pattern = """"https?://[^"]*"""".r
 | 
|  |    342 | 
 | 
|  |    343 | // drops the first and last character from a string
 | 
|  |    344 | def unquote(s: String) = s.drop(1).dropRight(1)
 | 
|  |    345 | 
 | 
|  |    346 | def get_all_URLs(page: String): Set[String] = 
 | 
|  |    347 |   http_pattern.findAllIn(page).map(unquote).toSet
 | 
|  |    348 | 
 | 
|  |    349 | // naive version of crawl - searches until a given depth,
 | 
|  |    350 | // visits pages potentially more than once
 | 
|  |    351 | def crawl(url: String, n: Int): Unit = {
 | 
|  |    352 |   if (n == 0) ()
 | 
|  |    353 |   else {
 | 
|  |    354 |     println(s"Visiting: $n $url")
 | 
|  |    355 |     for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
 | 
|  |    356 |   }
 | 
|  |    357 | }
 | 
|  |    358 | 
 | 
|  |    359 | // some starting URLs for the crawler
 | 
| 123 |    360 | val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
 | 
| 32 |    361 | //val startURL = """http://www.inf.kcl.ac.uk/staff/mcburney"""
 | 
|  |    362 | 
 | 
|  |    363 | crawl(startURL, 2)
 | 
|  |    364 | 
 | 
|  |    365 | 
 | 
|  |    366 | 
 | 
|  |    367 | // Further Information
 | 
|  |    368 | //=====================
 | 
|  |    369 | 
 | 
| 123 |    370 | // The Scala home page and general information is at
 | 
| 32 |    371 | //
 | 
|  |    372 | //  http://www.scala-lang.org
 | 
| 123 |    373 | //	http://docs.scala-lang.org
 | 
|  |    374 | //
 | 
|  |    375 | //
 | 
|  |    376 | // It should be fairly easy to install the Scala binary and
 | 
|  |    377 | // run Scala on the commandline. There are also at least 
 | 
|  |    378 | // four IDEs you can use with Scala:
 | 
|  |    379 | //
 | 
| 124 |    380 | //  (0) Some general information about setting up IDEs
 | 
| 123 |    381 | //	    with Scala support can be found at
 | 
|  |    382 | //
 | 
|  |    383 | //         http://docs.scala-lang.org/getting-started.html 
 | 
|  |    384 | //
 | 
| 124 |    385 | //
 | 
| 123 |    386 | //  (1) Eclipse for Scala (one big bundle)
 | 
|  |    387 | //
 | 
|  |    388 | //         http://scala-ide.org/download/sdk.html
 | 
|  |    389 | //  
 | 
|  |    390 | //  (2) IntelliJ (needs additional Plugins)
 | 
|  |    391 | //
 | 
|  |    392 | //         https://www.jetbrains.com/idea/
 | 
|  |    393 | //		   http://docs.scala-lang.org/getting-started-intellij-track/getting-started-with-scala-in-intellij.html	  
 | 
|  |    394 | //
 | 
|  |    395 | //  (3) Sublime (not free, but unlimited trial period; 
 | 
| 124 |    396 | //	    needs Scala and SublimeREPL plugin)
 | 
| 123 |    397 | //
 | 
|  |    398 | //         https://www.sublimetext.com
 | 
|  |    399 | //
 | 
|  |    400 | //  (4) Emacs (old-fashioned, but reliable)
 | 
|  |    401 | //
 | 
|  |    402 | //         https://www.gnu.org/software/emacs/
 | 
| 32 |    403 | //
 | 
| 123 |    404 | //      I use the old scala-tool support for Emacs distributed at
 | 
|  |    405 | //
 | 
|  |    406 | //         https://github.com/scala/scala-tool-support/tree/master/tool-support/emacs 
 | 
|  |    407 | //
 | 
|  |    408 | //      but there is also support for the newer Ensime Scala Mode
 | 
|  |    409 | //
 | 
|  |    410 | //         http://ensime.org/editors/emacs/scala-mode/   
 | 
|  |    411 | //   
 | 
|  |    412 | // There is also Scala support in the Atom editor, but my
 | 
|  |    413 | // experience is mixed. People also use Scala with Vim and Jedit.
 | 
| 124 |    414 | // Finally there is an online editor specifically designed for 
 | 
|  |    415 | // running Scala applications (but do not blame mne if you lose all 
 | 
|  |    416 | // what you typed in):
 | 
|  |    417 | //
 | 
|  |    418 | //      https://scalafiddle.io 
 | 
|  |    419 | //
 | 
|  |    420 | //
 | 
| 123 |    421 | //
 | 
|  |    422 | // All of the IDEs above support a REPL for Scala. Some of them have
 | 
|  |    423 | // the very nifty feature of a Scala Worksheet -- you just save your
 | 
|  |    424 | // file and it will be automatically evaluated and the result pasted
 | 
|  |    425 | // into your file. However, this way of writing Scala code never worked
 | 
|  |    426 | // for me. I just use the REPL.
 | 
|  |    427 | //
 | 
|  |    428 | //
 | 
|  |    429 | // Scala Library Docs
 | 
| 124 |    430 | //====================
 | 
| 123 |    431 | //
 | 
|  |    432 | //  http://www.scala-lang.org/api/current/
 | 
|  |    433 | //
 | 
|  |    434 | // Scala Tutorials
 | 
|  |    435 | //
 | 
|  |    436 | //  http://docs.scala-lang.org/tutorials/
 | 
|  |    437 | //
 | 
|  |    438 | // There are also a massive number of Scala tutorials on youtube
 | 
|  |    439 | // and there are tons of books and free material.
 | 
|  |    440 | //
 | 
| 32 |    441 | 
 | 
|  |    442 | 
 |