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