| 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 | // Hello World
 | 
|  |     17 | //=============
 | 
|  |     18 | 
 | 
|  |     19 | // an example of a stand-alone scala file;
 | 
|  |     20 | // in the coursework students must submit 
 | 
|  |     21 | // plain scala "work-sheets"
 | 
|  |     22 | 
 | 
|  |     23 | object Hello extends App { 
 | 
|  |     24 |   println("hello world")
 | 
|  |     25 | }
 | 
|  |     26 | 
 | 
|  |     27 | // can be called with
 | 
|  |     28 | //
 | 
|  |     29 | // $> scalac hello-world.scala
 | 
|  |     30 | // $> scala Hello
 | 
|  |     31 | //
 | 
|  |     32 | // $> java -cp /usr/local/src/scala/lib/scala-library.jar:. Hello
 | 
|  |     33 | 
 | 
|  |     34 | 
 | 
|  |     35 | 
 | 
|  |     36 | 
 | 
| 25 |     37 | // Collections
 | 
|  |     38 | //=============
 | 
| 14 |     39 | List(1,2,3,1)
 | 
|  |     40 | Set(1,2,3,1)
 | 
|  |     41 | 
 | 
|  |     42 | 1 to 10
 | 
|  |     43 | (1 to 10).toList
 | 
|  |     44 | 
 | 
|  |     45 | (1 until 10).toList
 | 
|  |     46 | 
 | 
| 18 |     47 | // an element in a list
 | 
| 33 |     48 | val lst = List(1, 2, 3, 1)
 | 
|  |     49 | lst(0)
 | 
|  |     50 | lst(2)
 | 
| 18 |     51 | 
 | 
| 34 |     52 | // some alterative syntax for lists
 | 
|  |     53 | 
 | 
| 23 |     54 | 1::2::3::Nil
 | 
|  |     55 | List(1, 2, 3) ::: List(4, 5, 6)
 | 
| 14 |     56 | 
 | 
| 25 |     57 | // Printing/Strings
 | 
|  |     58 | //==================
 | 
| 14 |     59 | 
 | 
|  |     60 | println("test")
 | 
| 15 |     61 | 
 | 
| 33 |     62 | val tst = "This is a " + "test\n" 
 | 
| 14 |     63 | println(tst)
 | 
|  |     64 | 
 | 
|  |     65 | val lst = List(1,2,3,1)
 | 
|  |     66 | 
 | 
|  |     67 | println(lst.toString)
 | 
|  |     68 | println(lst.mkString("\n"))
 | 
|  |     69 | 
 | 
| 33 |     70 | println(lst.mkString(", "))
 | 
|  |     71 | 
 | 
| 14 |     72 | // some methods take more than one argument
 | 
| 21 |     73 | println(lst.mkString("[", ",", "]"))
 | 
| 14 |     74 | 
 | 
| 32 |     75 | 
 | 
| 25 |     76 | // Conversion methods
 | 
|  |     77 | //====================
 | 
| 14 |     78 | 
 | 
|  |     79 | List(1,2,3,1).toString
 | 
|  |     80 | List(1,2,3,1).toSet
 | 
|  |     81 | "hello".toList
 | 
|  |     82 | 1.toDouble
 | 
|  |     83 | 
 | 
| 25 |     84 | 
 | 
| 32 |     85 | // useful list methods
 | 
|  |     86 | 
 | 
|  |     87 | List(1,2,3,4).length
 | 
| 25 |     88 | List(1,2,3,4).reverse
 | 
| 32 |     89 | List(1,2,3,4).max
 | 
|  |     90 | List(1,2,3,4).min
 | 
|  |     91 | List(1,2,3,4).sum
 | 
|  |     92 | List(1,2,3,4).take(2).sum
 | 
|  |     93 | List(1,2,3,4).drop(2).sum
 | 
| 123 |     94 | List(1,2,3,4,3)indexOf(3)
 | 
| 32 |     95 | 
 | 
| 36 |     96 | "1,2,3,4,5".split(",").mkString("\n")
 | 
|  |     97 | "1,2,3,4,5".split(",3,").mkString("\n")
 | 
| 25 |     98 | 
 | 
| 140 |     99 | // Types (slide)
 | 
| 25 |    100 | //=======
 | 
|  |    101 | 
 | 
|  |    102 | /* Scala is a strongly typed language
 | 
|  |    103 |  
 | 
| 34 |    104 |  * some base types
 | 
| 14 |    105 | 
 | 
| 25 |    106 |     Int, Long, BigInt, Float, Double
 | 
|  |    107 |     String, Char
 | 
|  |    108 |     Boolean
 | 
|  |    109 | 
 | 
| 34 |    110 |  * some compound types 
 | 
| 12 |    111 | 
 | 
| 25 |    112 |     List[Int],
 | 
|  |    113 |     Set[Double]
 | 
|  |    114 |     Pairs: (Int, String)        
 | 
|  |    115 |     List[(BigInt, String)]
 | 
|  |    116 | */
 | 
| 12 |    117 | 
 | 
| 25 |    118 | // Smart Strings
 | 
|  |    119 | //===============
 | 
|  |    120 | 
 | 
| 36 |    121 | println(">\n\n<")
 | 
| 23 |    122 | println(""">\n<""")
 | 
| 36 |    123 | println("""">\n<"""")
 | 
| 23 |    124 | 
 | 
|  |    125 | /* in Java
 | 
| 143 |    126 | val lyrics = "Sun dips down, the day has gone. \n" +
 | 
|  |    127 |              "Witches, wolves and giants yawn. \n" +
 | 
|  |    128 |              "Queen and dragon, troll and gnome: \n" +
 | 
|  |    129 |              "tired buddies head for home"
 | 
| 23 |    130 | */ 
 | 
|  |    131 | 
 | 
| 143 |    132 | val lyrics = """Sun dips down, the day has gone.
 | 
|  |    133 |                 |Witches, wolves and giants yawn.
 | 
|  |    134 |                 |Queen and dragon, troll and gnome:
 | 
|  |    135 |                 |tired buddies head for home""".stripMargin
 | 
| 23 |    136 | 
 | 
|  |    137 | println(lyrics)
 | 
|  |    138 | 
 | 
| 14 |    139 | 
 | 
| 25 |    140 | // Pairs/Tuples
 | 
|  |    141 | //==============
 | 
| 14 |    142 | 
 | 
|  |    143 | val p = (1, "one")
 | 
|  |    144 | p._1
 | 
|  |    145 | p._2
 | 
|  |    146 | 
 | 
|  |    147 | val t = (4,1,2,3)
 | 
|  |    148 | t._4
 | 
|  |    149 | 
 | 
| 25 |    150 | 
 | 
|  |    151 | // Function Definitions
 | 
|  |    152 | //======================
 | 
| 14 |    153 | 
 | 
| 123 |    154 | def incr(x: Int) : Int = x + 1
 | 
|  |    155 | def double(x: Int) : Int = x + x
 | 
|  |    156 | def square(x: Int) : Int = x * x
 | 
| 14 |    157 | 
 | 
| 25 |    158 | square(6)
 | 
| 21 |    159 | 
 | 
|  |    160 | 
 | 
| 36 |    161 | 
 | 
|  |    162 | // The general scheme for a function: you have to give a type 
 | 
|  |    163 | // to each argument and a return type of the function
 | 
|  |    164 | //
 | 
|  |    165 | //  def fname(arg1: ty1, arg2: ty2,..., argn: tyn): rty = {
 | 
|  |    166 | //    body 
 | 
|  |    167 | //  }
 | 
|  |    168 | 
 | 
|  |    169 | 
 | 
|  |    170 | 
 | 
| 123 |    171 | // If-Conditionals
 | 
|  |    172 | //=================
 | 
| 14 |    173 | 
 | 
| 143 |    174 | def fact(n: Int) : Int = 
 | 
| 14 |    175 |   if (n == 0) 1 else n * fact(n - 1)
 | 
|  |    176 | 
 | 
| 36 |    177 | 
 | 
|  |    178 | fact(5)
 | 
|  |    179 | fact(150)
 | 
|  |    180 | 
 | 
| 25 |    181 | /* boolean operators
 | 
|  |    182 |  
 | 
|  |    183 |    ==     equals
 | 
|  |    184 |    !      not
 | 
|  |    185 |    && ||  and, or
 | 
|  |    186 | */
 | 
| 15 |    187 | 
 | 
|  |    188 | 
 | 
| 14 |    189 | def fact2(n: BigInt): BigInt = 
 | 
|  |    190 |   if (n == 0) 1 else n * fact2(n - 1)
 | 
|  |    191 | 
 | 
| 25 |    192 | fact2(150)
 | 
|  |    193 | 
 | 
| 26 |    194 | 
 | 
| 14 |    195 | def fib(n: Int): Int =
 | 
|  |    196 |   if (n == 0) 1 else
 | 
| 26 |    197 |     if (n == 1) 1 else fib(n - 1) + fib(n - 2)
 | 
| 14 |    198 | 
 | 
|  |    199 | 
 | 
| 26 |    200 | //gcd - Euclid's algorithm
 | 
|  |    201 | 
 | 
| 123 |    202 | def gcd(a: Int, b: Int) : Int =
 | 
| 26 |    203 |   if (b == 0) a else gcd(b, a % b)
 | 
|  |    204 | 
 | 
|  |    205 | gcd(48, 18)
 | 
|  |    206 | 
 | 
| 14 |    207 | 
 | 
| 123 |    208 | def power(x: Int, n: Int) : Int =
 | 
|  |    209 |   if (n == 0) 1  else x * power(x, n - 1) 
 | 
|  |    210 | 
 | 
|  |    211 | power(5, 5)
 | 
|  |    212 | 
 | 
|  |    213 | 
 | 
| 25 |    214 | // String Interpolations
 | 
|  |    215 | //=======================
 | 
| 14 |    216 | 
 | 
| 26 |    217 | val n = 3
 | 
|  |    218 | println("The square of " + n + " is " + square(n) + ".")
 | 
|  |    219 | 
 | 
|  |    220 | println(s"The square of ${n} is ${square(n)}.")
 | 
|  |    221 | 
 | 
|  |    222 | 
 | 
|  |    223 | 
 | 
| 123 |    224 | def gcd_db(a: Int, b: Int) : Int = {
 | 
| 26 |    225 |   println(s"Function called with ${a} and ${b}.")
 | 
|  |    226 |   if (b == 0) a else gcd_db(b, a % b)
 | 
|  |    227 | }
 | 
|  |    228 | 
 | 
|  |    229 | gcd_db(48, 18)
 | 
|  |    230 | 
 | 
| 14 |    231 | 
 | 
| 124 |    232 | // Asserts/Testing
 | 
| 25 |    233 | //================
 | 
| 14 |    234 | 
 | 
| 32 |    235 | assert(gcd(48, 18) == 6)
 | 
|  |    236 | 
 | 
|  |    237 | assert(gcd(48, 18) == 5, "The gcd test failed")
 | 
|  |    238 | 
 | 
|  |    239 | 
 | 
| 26 |    240 | // For-Comprehensions (not For-Loops)
 | 
|  |    241 | //====================================
 | 
| 14 |    242 | 
 | 
|  |    243 | for (n <- (1 to 10).toList) yield square(n)
 | 
|  |    244 | 
 | 
| 25 |    245 | for (n <- (1 to 10).toList; 
 | 
|  |    246 |      m <- (1 to 10).toList) yield m * n
 | 
| 21 |    247 | 
 | 
|  |    248 | 
 | 
| 26 |    249 | val mult_table = 
 | 
|  |    250 |   for (n <- (1 to 10).toList; 
 | 
|  |    251 |        m <- (1 to 10).toList) yield m * n
 | 
|  |    252 | 
 | 
|  |    253 | mult_table.sliding(10,10).mkString("\n")
 | 
|  |    254 | 
 | 
| 25 |    255 | 
 | 
| 32 |    256 | // with if-predicates
 | 
|  |    257 | 
 | 
|  |    258 | for (n <- (1 to 3).toList; 
 | 
|  |    259 |      m <- (1 to 3).toList;
 | 
|  |    260 |      if (n + m) % 2 == 0) yield (n, m)
 | 
|  |    261 | 
 | 
| 148 |    262 | for (n <- (1 to 3).toList; 
 | 
|  |    263 |      m <- (1 to 3).toList;
 | 
|  |    264 |      if ((n + m) % 2 == 0)) yield (n, m)
 | 
| 32 |    265 | 
 | 
| 26 |    266 | // with patterns
 | 
|  |    267 | 
 | 
|  |    268 | for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n 
 | 
|  |    269 | 
 | 
|  |    270 | for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 
 | 
|  |    271 | 
 | 
| 25 |    272 | 
 | 
|  |    273 | 
 | 
| 36 |    274 | // with only a side-effect (no list is produced),
 | 
| 32 |    275 | // has no "yield"
 | 
|  |    276 | 
 | 
|  |    277 | for (n <- (1 to 10)) println(n)
 | 
|  |    278 | 
 | 
|  |    279 | 
 | 
| 140 |    280 | 
 | 
|  |    281 | 
 | 
|  |    282 | 
 | 
|  |    283 | 
 | 
|  |    284 | // concurrency (ONLY WORKS IN SCALA 2.11.8, not in SCALA 2.12)
 | 
|  |    285 | //             (would need to have this wrapped into a function, or
 | 
|  |    286 | //              REPL called with scala -Yrepl-class-based)
 | 
| 32 |    287 | for (n <- (1 to 10)) println(n)
 | 
|  |    288 | for (n <- (1 to 10).par) println(n)
 | 
|  |    289 | 
 | 
|  |    290 | 
 | 
| 36 |    291 | // for measuring time
 | 
| 140 |    292 | def time_needed[T](n: Int, code: => T) = {
 | 
| 32 |    293 |   val start = System.nanoTime()
 | 
| 140 |    294 |   for (i <- (0 to n)) code
 | 
| 32 |    295 |   val end = System.nanoTime()
 | 
| 140 |    296 |   (end - start) / 1.0e9
 | 
| 32 |    297 | }
 | 
|  |    298 | 
 | 
| 140 |    299 | 
 | 
| 32 |    300 | val list = (1 to 1000000).toList
 | 
|  |    301 | time_needed(10, for (n <- list) yield n + 42)
 | 
|  |    302 | time_needed(10, for (n <- list.par) yield n + 42)
 | 
|  |    303 | 
 | 
|  |    304 | 
 | 
| 170 |    305 | // mutable vs immutable factorial
 | 
|  |    306 | def fact_mu(n: Long): Long = {
 | 
|  |    307 |   var result : Long = 1
 | 
|  |    308 |   var i = 1
 | 
|  |    309 |   while (i <= n) {
 | 
|  |    310 |     result = result * i
 | 
|  |    311 |     i = i + 1
 | 
|  |    312 |   }
 | 
|  |    313 |   result
 | 
|  |    314 | }
 | 
| 140 |    315 | 
 | 
| 170 |    316 | def fact_im(num: Long): Long = {
 | 
|  |    317 |   if (num == 1) num else
 | 
|  |    318 |     num * fact_im(num - 1)
 | 
|  |    319 | }
 | 
| 140 |    320 | 
 | 
| 170 |    321 | def test() = {
 | 
|  |    322 |   for (i <- (0 to 10).par) yield {
 | 
|  |    323 |     val l1 = for (n <- (List.fill(100000)(20 to 21)).flatten.par) yield fact_mu(n)
 | 
|  |    324 |     val l2 = for (n <- (List.fill(100000)(20 to 21)).flatten.par) yield fact_im(n) 
 | 
|  |    325 |     l1.sum - l2.sum
 | 
|  |    326 |   }
 | 
|  |    327 | }
 | 
|  |    328 | 
 | 
|  |    329 | test().sum
 | 
|  |    330 | println(l1.sum - l2.sum)
 | 
| 140 |    331 | 
 | 
| 25 |    332 | // Webpages
 | 
|  |    333 | //==========
 | 
| 32 |    334 | 
 | 
|  |    335 | import io.Source
 | 
|  |    336 | 
 | 
| 36 |    337 | // obtaining a webpage
 | 
| 123 |    338 | val url = """https://nms.kcl.ac.uk/christian.urban/""" 
 | 
| 32 |    339 | Source.fromURL(url)("ISO-8859-1").mkString
 | 
|  |    340 | 
 | 
|  |    341 | 
 | 
| 140 |    342 | // another example
 | 
|  |    343 | //val url = """http://api.postcodes.io/postcodes/CR84LQ""" 
 | 
|  |    344 | 
 | 
|  |    345 | 
 | 
| 137 |    346 | // a function for looking up constituency data
 | 
|  |    347 | def consty_lookup(pcode: String) : String = {
 | 
|  |    348 |   val url = "http://api.postcodes.io/postcodes/" + pcode
 | 
|  |    349 |   Source.fromURL(url).mkString.split(",")(16)
 | 
| 32 |    350 | }
 | 
|  |    351 | 
 | 
| 137 |    352 | consty_lookup("CR84LQ")
 | 
|  |    353 | consty_lookup("WC2B4BG")
 | 
| 32 |    354 | 
 | 
|  |    355 | 
 | 
| 137 |    356 | val places = 
 | 
|  |    357 |   List("CR84LQ", "WC2B4BG", "KY169QT", "CB11LY", "CB39AX")
 | 
| 32 |    358 | 
 | 
| 137 |    359 | for (s <- places) println(consty_lookup(s))
 | 
|  |    360 | 
 | 
|  |    361 | 
 | 
| 32 |    362 | 
 | 
|  |    363 | 
 | 
| 123 |    364 | // A Web Crawler 
 | 
| 32 |    365 | //===============
 | 
| 36 |    366 | //
 | 
| 123 |    367 | // the idea is to look for dead links using the
 | 
|  |    368 | // regular expression "https?://[^"]*"
 | 
| 32 |    369 | 
 | 
|  |    370 | import io.Source
 | 
|  |    371 | import scala.util._
 | 
|  |    372 | 
 | 
|  |    373 | // gets the first 10K of a web-page
 | 
|  |    374 | def get_page(url: String) : String = {
 | 
|  |    375 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | 
|  |    376 |     getOrElse { println(s"  Problem with: $url"); ""}
 | 
|  |    377 | }
 | 
|  |    378 | 
 | 
|  |    379 | // regex for URLs
 | 
|  |    380 | val http_pattern = """"https?://[^"]*"""".r
 | 
|  |    381 | 
 | 
|  |    382 | // drops the first and last character from a string
 | 
|  |    383 | def unquote(s: String) = s.drop(1).dropRight(1)
 | 
|  |    384 | 
 | 
|  |    385 | def get_all_URLs(page: String): Set[String] = 
 | 
|  |    386 |   http_pattern.findAllIn(page).map(unquote).toSet
 | 
|  |    387 | 
 | 
|  |    388 | // naive version of crawl - searches until a given depth,
 | 
|  |    389 | // visits pages potentially more than once
 | 
| 140 |    390 | def crawl(url: String, n: Int) : Unit = {
 | 
| 32 |    391 |   if (n == 0) ()
 | 
|  |    392 |   else {
 | 
|  |    393 |     println(s"Visiting: $n $url")
 | 
|  |    394 |     for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
 | 
|  |    395 |   }
 | 
|  |    396 | }
 | 
|  |    397 | 
 | 
|  |    398 | // some starting URLs for the crawler
 | 
| 123 |    399 | val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
 | 
| 137 |    400 | //val startURL = """https://nms.kcl.ac.uk/luc.moreau/index.html"""
 | 
| 32 |    401 | 
 | 
|  |    402 | crawl(startURL, 2)
 | 
|  |    403 | 
 | 
|  |    404 | 
 | 
|  |    405 | 
 | 
|  |    406 | // Further Information
 | 
|  |    407 | //=====================
 | 
|  |    408 | 
 | 
| 123 |    409 | // The Scala home page and general information is at
 | 
| 32 |    410 | //
 | 
|  |    411 | //  http://www.scala-lang.org
 | 
| 123 |    412 | //	http://docs.scala-lang.org
 | 
|  |    413 | //
 | 
|  |    414 | //
 | 
|  |    415 | // It should be fairly easy to install the Scala binary and
 | 
|  |    416 | // run Scala on the commandline. There are also at least 
 | 
|  |    417 | // four IDEs you can use with Scala:
 | 
|  |    418 | //
 | 
| 124 |    419 | //  (0) Some general information about setting up IDEs
 | 
| 123 |    420 | //	    with Scala support can be found at
 | 
|  |    421 | //
 | 
|  |    422 | //         http://docs.scala-lang.org/getting-started.html 
 | 
|  |    423 | //
 | 
| 124 |    424 | //
 | 
| 123 |    425 | //  (1) Eclipse for Scala (one big bundle)
 | 
|  |    426 | //
 | 
|  |    427 | //         http://scala-ide.org/download/sdk.html
 | 
|  |    428 | //  
 | 
|  |    429 | //  (2) IntelliJ (needs additional Plugins)
 | 
|  |    430 | //
 | 
|  |    431 | //         https://www.jetbrains.com/idea/
 | 
|  |    432 | //		   http://docs.scala-lang.org/getting-started-intellij-track/getting-started-with-scala-in-intellij.html	  
 | 
|  |    433 | //
 | 
|  |    434 | //  (3) Sublime (not free, but unlimited trial period; 
 | 
| 124 |    435 | //	    needs Scala and SublimeREPL plugin)
 | 
| 123 |    436 | //
 | 
|  |    437 | //         https://www.sublimetext.com
 | 
|  |    438 | //
 | 
|  |    439 | //  (4) Emacs (old-fashioned, but reliable)
 | 
|  |    440 | //
 | 
|  |    441 | //         https://www.gnu.org/software/emacs/
 | 
| 32 |    442 | //
 | 
| 123 |    443 | //      I use the old scala-tool support for Emacs distributed at
 | 
|  |    444 | //
 | 
|  |    445 | //         https://github.com/scala/scala-tool-support/tree/master/tool-support/emacs 
 | 
|  |    446 | //
 | 
|  |    447 | //      but there is also support for the newer Ensime Scala Mode
 | 
|  |    448 | //
 | 
|  |    449 | //         http://ensime.org/editors/emacs/scala-mode/   
 | 
|  |    450 | //   
 | 
|  |    451 | // There is also Scala support in the Atom editor, but my
 | 
|  |    452 | // experience is mixed. People also use Scala with Vim and Jedit.
 | 
| 124 |    453 | // Finally there is an online editor specifically designed for 
 | 
|  |    454 | // running Scala applications (but do not blame mne if you lose all 
 | 
|  |    455 | // what you typed in):
 | 
|  |    456 | //
 | 
|  |    457 | //      https://scalafiddle.io 
 | 
|  |    458 | //
 | 
|  |    459 | //
 | 
| 123 |    460 | //
 | 
|  |    461 | // All of the IDEs above support a REPL for Scala. Some of them have
 | 
|  |    462 | // the very nifty feature of a Scala Worksheet -- you just save your
 | 
|  |    463 | // file and it will be automatically evaluated and the result pasted
 | 
|  |    464 | // into your file. However, this way of writing Scala code never worked
 | 
|  |    465 | // for me. I just use the REPL.
 | 
|  |    466 | //
 | 
|  |    467 | //
 | 
|  |    468 | // Scala Library Docs
 | 
| 124 |    469 | //====================
 | 
| 123 |    470 | //
 | 
|  |    471 | //  http://www.scala-lang.org/api/current/
 | 
|  |    472 | //
 | 
|  |    473 | // Scala Tutorials
 | 
|  |    474 | //
 | 
|  |    475 | //  http://docs.scala-lang.org/tutorials/
 | 
|  |    476 | //
 | 
|  |    477 | // There are also a massive number of Scala tutorials on youtube
 | 
|  |    478 | // and there are tons of books and free material.
 | 
|  |    479 | //
 | 
| 32 |    480 | 
 | 
|  |    481 | 
 | 
| 170 |    482 | 
 | 
|  |    483 | 
 | 
|  |    484 | 
 | 
|  |    485 | 
 | 
|  |    486 | 
 | 
|  |    487 | 
 | 
|  |    488 | 
 | 
|  |    489 | // advantage of case classes
 | 
|  |    490 | //
 | 
|  |    491 | case class Participant(name: String, score: Int, active: Boolean)
 | 
|  |    492 | 
 | 
|  |    493 | val ps = Seq(Participant("Jack", 34, true),
 | 
|  |    494 |              Participant("Tom", 51, true),
 | 
|  |    495 |              Participant("Bob", 90, false))
 | 
|  |    496 |              
 | 
|  |    497 | ps.filter(_.score < 50).
 | 
|  |    498 |    filter(_.active).
 | 
|  |    499 |    map(_.copy(active = false))
 | 
|  |    500 | 
 | 
|  |    501 | 
 | 
|  |    502 | 
 | 
|  |    503 | // another example why state is bad...does not work yet
 | 
|  |    504 | 
 | 
|  |    505 | // for measuring time
 | 
|  |    506 | def time_needed[T](n: Int, code: => T) = {
 | 
|  |    507 |   val start = System.nanoTime()
 | 
|  |    508 |   for (i <- (0 to n)) code
 | 
|  |    509 |   val end = System.nanoTime()
 | 
|  |    510 |   (end - start) / 1.0e9
 | 
|  |    511 | }
 | 
|  |    512 | 
 | 
|  |    513 | def santa_state(plan: List[Char]) : Int = {  
 | 
|  |    514 | 
 | 
|  |    515 |   var floor = 0
 | 
|  |    516 | 
 | 
|  |    517 |   for (i <- plan.par) {
 | 
|  |    518 |     if (i == '(') {
 | 
|  |    519 |       floor += 1
 | 
|  |    520 |     } else {
 | 
|  |    521 |       floor -= 1
 | 
|  |    522 |     }
 | 
|  |    523 |   }
 | 
|  |    524 |   
 | 
|  |    525 |   floor
 | 
|  |    526 | }
 | 
|  |    527 | 
 | 
|  |    528 | def i(c: Char) = if (c == '(') 1 else -1
 | 
|  |    529 | 
 | 
|  |    530 | def santa_imutable(plan: List[Char]) : Int =
 | 
|  |    531 |   plan.par.map(i(_)).reduce(_ + _)
 | 
|  |    532 | 
 | 
|  |    533 | santa_state("(((((()))))".toList)
 | 
|  |    534 | santa_imutable("(((((()))))".toList)
 | 
|  |    535 | 
 | 
|  |    536 | def randomString(length: Int) = 
 | 
|  |    537 |   List.fill(length)((40 + scala.util.Random.nextInt(2)).toChar)
 | 
|  |    538 | 
 | 
|  |    539 | 
 | 
|  |    540 | santa_state(randomString(100))
 | 
|  |    541 | 
 | 
|  |    542 | val large_string = randomString(3000000)
 | 
|  |    543 | 
 | 
|  |    544 | time_needed(10, santa_state(large_string))
 | 
|  |    545 | time_needed(10, santa_imutable(large_string))
 |