| 51 |      1 | // Scala Lecture 1
 | 
|  |      2 | //=================
 | 
| 14 |      3 | 
 | 
| 26 |      4 | // Value assignments
 | 
| 25 |      5 | // (variable names should be lower case)
 | 
|  |      6 | //======================================
 | 
| 21 |      7 | 
 | 
| 14 |      8 | val x = 42
 | 
|  |      9 | val y = 3 + 4
 | 
|  |     10 | 
 | 
|  |     11 | 
 | 
| 25 |     12 | // Collections
 | 
|  |     13 | //=============
 | 
| 14 |     14 | List(1,2,3,1)
 | 
|  |     15 | Set(1,2,3,1)
 | 
|  |     16 | 
 | 
|  |     17 | 1 to 10
 | 
|  |     18 | (1 to 10).toList
 | 
|  |     19 | 
 | 
|  |     20 | (1 until 10).toList
 | 
|  |     21 | 
 | 
| 18 |     22 | // an element in a list
 | 
| 33 |     23 | val lst = List(1, 2, 3, 1)
 | 
|  |     24 | lst(0)
 | 
|  |     25 | lst(2)
 | 
| 18 |     26 | 
 | 
| 34 |     27 | // some alterative syntax for lists
 | 
|  |     28 | 
 | 
| 23 |     29 | 1::2::3::Nil
 | 
|  |     30 | List(1, 2, 3) ::: List(4, 5, 6)
 | 
| 14 |     31 | 
 | 
| 25 |     32 | // Printing/Strings
 | 
|  |     33 | //==================
 | 
| 14 |     34 | 
 | 
|  |     35 | println("test")
 | 
| 15 |     36 | 
 | 
| 33 |     37 | val tst = "This is a " + "test\n" 
 | 
| 14 |     38 | println(tst)
 | 
|  |     39 | 
 | 
|  |     40 | val lst = List(1,2,3,1)
 | 
|  |     41 | 
 | 
|  |     42 | println(lst.toString)
 | 
|  |     43 | println(lst.mkString("\n"))
 | 
|  |     44 | 
 | 
| 33 |     45 | println(lst.mkString(", "))
 | 
|  |     46 | 
 | 
| 14 |     47 | // some methods take more than one argument
 | 
| 21 |     48 | println(lst.mkString("[", ",", "]"))
 | 
| 14 |     49 | 
 | 
| 32 |     50 | 
 | 
| 25 |     51 | // Conversion methods
 | 
|  |     52 | //====================
 | 
| 14 |     53 | 
 | 
|  |     54 | List(1,2,3,1).toString
 | 
|  |     55 | List(1,2,3,1).toSet
 | 
|  |     56 | "hello".toList
 | 
|  |     57 | 1.toDouble
 | 
|  |     58 | 
 | 
| 25 |     59 | 
 | 
| 32 |     60 | // useful list methods
 | 
|  |     61 | 
 | 
|  |     62 | List(1,2,3,4).length
 | 
| 25 |     63 | List(1,2,3,4).reverse
 | 
| 32 |     64 | List(1,2,3,4).max
 | 
|  |     65 | List(1,2,3,4).min
 | 
|  |     66 | List(1,2,3,4).sum
 | 
|  |     67 | List(1,2,3,4).take(2).sum
 | 
|  |     68 | List(1,2,3,4).drop(2).sum
 | 
|  |     69 | List(1,2,3,4,3).indexOf(3)
 | 
|  |     70 | 
 | 
| 36 |     71 | "1,2,3,4,5".split(",").mkString("\n")
 | 
|  |     72 | "1,2,3,4,5".split(",3,").mkString("\n")
 | 
| 25 |     73 | 
 | 
|  |     74 | // Types
 | 
|  |     75 | //=======
 | 
|  |     76 | 
 | 
|  |     77 | /* Scala is a strongly typed language
 | 
|  |     78 |  
 | 
| 34 |     79 |  * some base types
 | 
| 14 |     80 | 
 | 
| 25 |     81 |     Int, Long, BigInt, Float, Double
 | 
|  |     82 |     String, Char
 | 
|  |     83 |     Boolean
 | 
|  |     84 | 
 | 
| 34 |     85 |  * some compound types 
 | 
| 12 |     86 | 
 | 
| 25 |     87 |     List[Int],
 | 
|  |     88 |     Set[Double]
 | 
|  |     89 |     Pairs: (Int, String)        
 | 
|  |     90 |     List[(BigInt, String)]
 | 
|  |     91 | */
 | 
| 12 |     92 | 
 | 
| 25 |     93 | // Smart Strings
 | 
|  |     94 | //===============
 | 
|  |     95 | 
 | 
| 36 |     96 | println(">\n\n<")
 | 
| 23 |     97 | println(""">\n<""")
 | 
| 36 |     98 | println("""">\n<"""")
 | 
| 23 |     99 | 
 | 
|  |    100 | /* in Java
 | 
|  |    101 | val lyrics = "Baa, Baa, Black Sheep \n" +
 | 
|  |    102 |              "Have you any wool? \n" +
 | 
|  |    103 |              "Yes, sir, yes sir \n" +
 | 
|  |    104 |              "Three bags full"
 | 
|  |    105 | */ 
 | 
|  |    106 | 
 | 
|  |    107 | val lyrics = """Baa, Baa, Black Sheep  
 | 
|  |    108 |                 |Have you any wool?
 | 
|  |    109 |                 |Yes, sir, yes sir
 | 
|  |    110 |                 |Three bags full""".stripMargin
 | 
|  |    111 | 
 | 
|  |    112 | println(lyrics)
 | 
|  |    113 | 
 | 
| 14 |    114 | 
 | 
| 25 |    115 | // Pairs/Tuples
 | 
|  |    116 | //==============
 | 
| 14 |    117 | 
 | 
|  |    118 | val p = (1, "one")
 | 
|  |    119 | p._1
 | 
|  |    120 | p._2
 | 
|  |    121 | 
 | 
|  |    122 | val t = (4,1,2,3)
 | 
|  |    123 | t._4
 | 
|  |    124 | 
 | 
| 25 |    125 | // Hello World
 | 
|  |    126 | //=============
 | 
|  |    127 | 
 | 
| 32 |    128 | // an example of a stand-alone scala file;
 | 
|  |    129 | // in the coursework students must submit 
 | 
|  |    130 | // plain scala "work-sheets"
 | 
| 25 |    131 | 
 | 
| 32 |    132 | object Hello extends App { 
 | 
|  |    133 |   println("hello world")
 | 
|  |    134 | }
 | 
|  |    135 | 
 | 
|  |    136 | // can be called with
 | 
|  |    137 | //
 | 
|  |    138 | // $> scalac hello-world.scala
 | 
|  |    139 | // $> scala Hello
 | 
|  |    140 | //
 | 
|  |    141 | // $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
 | 
| 25 |    142 | 
 | 
|  |    143 | 
 | 
|  |    144 | // Function Definitions
 | 
|  |    145 | //======================
 | 
| 14 |    146 | 
 | 
|  |    147 | def square(x: Int): Int = x * x
 | 
|  |    148 | 
 | 
| 25 |    149 | square(6)
 | 
| 21 |    150 | 
 | 
|  |    151 | 
 | 
| 36 |    152 | 
 | 
|  |    153 | // The general scheme for a function: you have to give a type 
 | 
|  |    154 | // to each argument and a return type of the function
 | 
|  |    155 | //
 | 
|  |    156 | //  def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
 | 
|  |    157 | //    body 
 | 
|  |    158 | //  }
 | 
|  |    159 | 
 | 
|  |    160 | 
 | 
|  |    161 | 
 | 
| 25 |    162 | // If control structure
 | 
|  |    163 | //======================
 | 
| 14 |    164 | 
 | 
|  |    165 | def fact(n: Int): Int = 
 | 
|  |    166 |   if (n == 0) 1 else n * fact(n - 1)
 | 
|  |    167 | 
 | 
| 36 |    168 | 
 | 
|  |    169 | fact(5)
 | 
|  |    170 | fact(150)
 | 
|  |    171 | 
 | 
| 25 |    172 | /* boolean operators
 | 
|  |    173 |  
 | 
|  |    174 |    ==     equals
 | 
|  |    175 |    !      not
 | 
|  |    176 |    && ||  and, or
 | 
|  |    177 | */
 | 
| 15 |    178 | 
 | 
|  |    179 | 
 | 
| 14 |    180 | def fact2(n: BigInt): BigInt = 
 | 
|  |    181 |   if (n == 0) 1 else n * fact2(n - 1)
 | 
|  |    182 | 
 | 
| 25 |    183 | fact2(150)
 | 
|  |    184 | 
 | 
| 26 |    185 | 
 | 
| 14 |    186 | def fib(n: Int): Int =
 | 
|  |    187 |   if (n == 0) 1 else
 | 
| 26 |    188 |     if (n == 1) 1 else fib(n - 1) + fib(n - 2)
 | 
| 14 |    189 | 
 | 
|  |    190 | 
 | 
| 26 |    191 | //gcd - Euclid's algorithm
 | 
|  |    192 | 
 | 
|  |    193 | def gcd(a: Int, b: Int): Int =
 | 
|  |    194 |   if (b == 0) a else gcd(b, a % b)
 | 
|  |    195 | 
 | 
|  |    196 | gcd(48, 18)
 | 
|  |    197 | 
 | 
| 14 |    198 | 
 | 
| 25 |    199 | // String Interpolations
 | 
|  |    200 | //=======================
 | 
| 14 |    201 | 
 | 
| 26 |    202 | val n = 3
 | 
|  |    203 | println("The square of " + n + " is " + square(n) + ".")
 | 
|  |    204 | 
 | 
|  |    205 | println(s"The square of ${n} is ${square(n)}.")
 | 
|  |    206 | 
 | 
|  |    207 | 
 | 
|  |    208 | 
 | 
|  |    209 | def gcd_db(a: Int, b: Int): Int = {
 | 
|  |    210 |   println(s"Function called with ${a} and ${b}.")
 | 
|  |    211 |   if (b == 0) a else gcd_db(b, a % b)
 | 
|  |    212 | }
 | 
|  |    213 | 
 | 
|  |    214 | gcd_db(48, 18)
 | 
|  |    215 | 
 | 
| 14 |    216 | 
 | 
| 25 |    217 | // Assert/Testing
 | 
|  |    218 | //================
 | 
| 14 |    219 | 
 | 
| 32 |    220 | assert(gcd(48, 18) == 6)
 | 
|  |    221 | 
 | 
|  |    222 | assert(gcd(48, 18) == 5, "The gcd test failed")
 | 
|  |    223 | 
 | 
|  |    224 | 
 | 
| 26 |    225 | // For-Comprehensions (not For-Loops)
 | 
|  |    226 | //====================================
 | 
| 14 |    227 | 
 | 
|  |    228 | for (n <- (1 to 10).toList) yield square(n)
 | 
|  |    229 | 
 | 
| 25 |    230 | for (n <- (1 to 10).toList; 
 | 
|  |    231 |      m <- (1 to 10).toList) yield m * n
 | 
| 21 |    232 | 
 | 
|  |    233 | 
 | 
| 26 |    234 | val mult_table = 
 | 
|  |    235 |   for (n <- (1 to 10).toList; 
 | 
|  |    236 |        m <- (1 to 10).toList) yield m * n
 | 
|  |    237 | 
 | 
|  |    238 | mult_table.sliding(10,10).mkString("\n")
 | 
|  |    239 | 
 | 
| 25 |    240 | 
 | 
| 32 |    241 | // with if-predicates
 | 
|  |    242 | 
 | 
|  |    243 | for (n <- (1 to 3).toList; 
 | 
|  |    244 |      m <- (1 to 3).toList;
 | 
|  |    245 |      if (n + m) % 2 == 0) yield (n, m)
 | 
|  |    246 | 
 | 
|  |    247 | 
 | 
|  |    248 | 
 | 
| 26 |    249 | // with patterns
 | 
|  |    250 | 
 | 
|  |    251 | for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n 
 | 
|  |    252 | 
 | 
|  |    253 | for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 
 | 
|  |    254 | 
 | 
| 25 |    255 | 
 | 
|  |    256 | 
 | 
| 36 |    257 | // with only a side-effect (no list is produced),
 | 
| 32 |    258 | // has no "yield"
 | 
|  |    259 | 
 | 
|  |    260 | for (n <- (1 to 10)) println(n)
 | 
|  |    261 | 
 | 
|  |    262 | 
 | 
| 36 |    263 | // concurrency (ONLY WORKS IN SCALA 2.11.8, not in SCALA 2.12.0)
 | 
| 32 |    264 | for (n <- (1 to 10)) println(n)
 | 
|  |    265 | for (n <- (1 to 10).par) println(n)
 | 
|  |    266 | 
 | 
|  |    267 | 
 | 
| 36 |    268 | // for measuring time
 | 
| 32 |    269 | def time_needed[T](i: Int, code: => T) = {
 | 
|  |    270 |   val start = System.nanoTime()
 | 
|  |    271 |   for (j <- 1 to i) code
 | 
|  |    272 |   val end = System.nanoTime()
 | 
|  |    273 |   ((end - start) / i / 1.0e9) + " secs"
 | 
|  |    274 | }
 | 
|  |    275 | 
 | 
|  |    276 | val list = (1 to 1000000).toList
 | 
|  |    277 | time_needed(10, for (n <- list) yield n + 42)
 | 
|  |    278 | time_needed(10, for (n <- list.par) yield n + 42)
 | 
|  |    279 | 
 | 
|  |    280 | 
 | 
|  |    281 | 
 | 
| 25 |    282 | // Webpages
 | 
|  |    283 | //==========
 | 
| 32 |    284 | 
 | 
|  |    285 | import io.Source
 | 
|  |    286 | 
 | 
| 36 |    287 | // obtaining a webpage
 | 
| 32 |    288 | val url = """http://www.inf.kcl.ac.uk/staff/urbanc/""" 
 | 
|  |    289 | Source.fromURL(url)("ISO-8859-1").mkString
 | 
|  |    290 | 
 | 
|  |    291 | 
 | 
| 36 |    292 | // function for looking up stockmarket data 
 | 
| 32 |    293 | def price_lookup(symbol: String): String = {
 | 
|  |    294 |   val url = "http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=snl1"
 | 
|  |    295 |   Source.fromURL(url).mkString.drop(1).dropRight(2)
 | 
|  |    296 | }
 | 
|  |    297 | 
 | 
|  |    298 | price_lookup("GOOG")
 | 
|  |    299 | price_lookup("AAPL")
 | 
|  |    300 | 
 | 
|  |    301 | 
 | 
|  |    302 | val companies = 
 | 
|  |    303 |   List("GOOG", "AAPL", "MSFT", "IBM", "FB", "YHOO", "AMZN", "BIDU")
 | 
|  |    304 | 
 | 
|  |    305 | for (s <- companies.par) println(price_lookup(s))
 | 
|  |    306 | 
 | 
|  |    307 | 
 | 
|  |    308 | // A Web Crawler
 | 
|  |    309 | //===============
 | 
| 36 |    310 | //
 | 
|  |    311 | // the idea is to look for dead links
 | 
| 32 |    312 | 
 | 
|  |    313 | import io.Source
 | 
|  |    314 | import scala.util.matching.Regex
 | 
|  |    315 | import scala.util._
 | 
|  |    316 | 
 | 
|  |    317 | // gets the first 10K of a web-page
 | 
|  |    318 | def get_page(url: String) : String = {
 | 
|  |    319 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | 
|  |    320 |     getOrElse { println(s"  Problem with: $url"); ""}
 | 
|  |    321 | }
 | 
|  |    322 | 
 | 
|  |    323 | // regex for URLs
 | 
|  |    324 | val http_pattern = """"https?://[^"]*"""".r
 | 
|  |    325 | 
 | 
|  |    326 | // drops the first and last character from a string
 | 
|  |    327 | def unquote(s: String) = s.drop(1).dropRight(1)
 | 
|  |    328 | 
 | 
|  |    329 | def get_all_URLs(page: String): Set[String] = 
 | 
|  |    330 |   http_pattern.findAllIn(page).map(unquote).toSet
 | 
|  |    331 | 
 | 
|  |    332 | // naive version of crawl - searches until a given depth,
 | 
|  |    333 | // visits pages potentially more than once
 | 
|  |    334 | def crawl(url: String, n: Int): Unit = {
 | 
|  |    335 |   if (n == 0) ()
 | 
|  |    336 |   else {
 | 
|  |    337 |     println(s"Visiting: $n $url")
 | 
|  |    338 |     for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
 | 
|  |    339 |   }
 | 
|  |    340 | }
 | 
|  |    341 | 
 | 
|  |    342 | // some starting URLs for the crawler
 | 
|  |    343 | val startURL = """http://www.inf.kcl.ac.uk/staff/urbanc"""
 | 
|  |    344 | //val startURL = """http://www.inf.kcl.ac.uk/staff/mcburney"""
 | 
|  |    345 | 
 | 
|  |    346 | crawl(startURL, 2)
 | 
|  |    347 | 
 | 
|  |    348 | 
 | 
|  |    349 | 
 | 
|  |    350 | // Further Information
 | 
|  |    351 | //=====================
 | 
|  |    352 | 
 | 
|  |    353 | // Scala download
 | 
|  |    354 | //
 | 
|  |    355 | //  http://www.scala-lang.org
 | 
|  |    356 | 
 | 
|  |    357 | // Eclipse for Scala
 | 
|  |    358 | //
 | 
|  |    359 | //  http://scala-ide.org/download/sdk.html
 | 
|  |    360 | 
 | 
|  |    361 | 
 | 
|  |    362 | // library docs
 | 
|  |    363 | //
 | 
|  |    364 | //  http://www.scala-lang.org/api/current/
 | 
|  |    365 | 
 | 
|  |    366 | // tutorials
 | 
|  |    367 | //
 | 
|  |    368 | //  http://docs.scala-lang.org/tutorials/
 |