| 51 |      1 | // Scala Lecture 2
 | 
|  |      2 | //=================
 | 
|  |      3 | 
 | 
| 204 |      4 | // UNFINISHED BUSINESS from Lecture 1
 | 
|  |      5 | //====================================
 | 
|  |      6 | 
 | 
|  |      7 | 
 | 
|  |      8 | // for measuring time
 | 
|  |      9 | def time_needed[T](n: Int, code: => T) = {
 | 
|  |     10 |   val start = System.nanoTime()
 | 
|  |     11 |   for (i <- (0 to n)) code
 | 
|  |     12 |   val end = System.nanoTime()
 | 
|  |     13 |   (end - start) / 1.0e9
 | 
|  |     14 | }
 | 
|  |     15 | 
 | 
|  |     16 | 
 | 
|  |     17 | val list = (1 to 1000000).toList
 | 
|  |     18 | time_needed(10, for (n <- list) yield n + 42)
 | 
|  |     19 | time_needed(10, for (n <- list.par) yield n + 42)
 | 
|  |     20 | 
 | 
| 268 |     21 | // (needs a library and 'magic' option -Yrepl-class-based)
 | 
| 204 |     22 | 
 | 
| 212 |     23 | 
 | 
| 310 |     24 | 
 | 
|  |     25 | 
 | 
| 212 |     26 | // Just for Fun: Mutable vs Immutable
 | 
|  |     27 | //====================================
 | 
| 204 |     28 | //
 | 
|  |     29 | // - no vars, no ++i, no +=
 | 
|  |     30 | // - no mutable data-structures (no Arrays, no ListBuffers)
 | 
|  |     31 | 
 | 
|  |     32 | 
 | 
| 212 |     33 | // Q: Count how many elements are in the intersections of 
 | 
|  |     34 | //    two sets?
 | 
| 204 |     35 | 
 | 
|  |     36 | def count_intersection(A: Set[Int], B: Set[Int]) : Int = {
 | 
|  |     37 |   var count = 0
 | 
|  |     38 |   for (x <- A; if B contains x) count += 1 
 | 
|  |     39 |   count
 | 
|  |     40 | }
 | 
|  |     41 | 
 | 
|  |     42 | val A = (1 to 1000).toSet
 | 
|  |     43 | val B = (1 to 1000 by 4).toSet
 | 
|  |     44 | 
 | 
|  |     45 | count_intersection(A, B)
 | 
|  |     46 | 
 | 
|  |     47 | // but do not try to add .par to the for-loop above
 | 
|  |     48 | 
 | 
|  |     49 | 
 | 
|  |     50 | //propper parallel version
 | 
|  |     51 | def count_intersection2(A: Set[Int], B: Set[Int]) : Int = 
 | 
|  |     52 |   A.par.count(x => B contains x)
 | 
|  |     53 | 
 | 
|  |     54 | count_intersection2(A, B)
 | 
|  |     55 | 
 | 
|  |     56 | 
 | 
|  |     57 | val A = (1 to 1000000).toSet
 | 
|  |     58 | val B = (1 to 1000000 by 4).toSet
 | 
|  |     59 | 
 | 
|  |     60 | time_needed(100, count_intersection(A, B))
 | 
|  |     61 | time_needed(100, count_intersection2(A, B))
 | 
|  |     62 | 
 | 
|  |     63 | 
 | 
|  |     64 | 
 | 
|  |     65 | // For-Comprehensions Again
 | 
|  |     66 | //==========================
 | 
|  |     67 | 
 | 
|  |     68 | // the first produces a result, while the second does not
 | 
|  |     69 | for (n <- List(1, 2, 3, 4, 5)) yield n * n
 | 
|  |     70 | 
 | 
|  |     71 | 
 | 
|  |     72 | for (n <- List(1, 2, 3, 4, 5)) println(n)
 | 
|  |     73 | 
 | 
|  |     74 | 
 | 
| 310 |     75 | // String Interpolations
 | 
|  |     76 | //=======================
 | 
|  |     77 | 
 | 
|  |     78 | val n = 3
 | 
|  |     79 | println("The square of " + n + " is " + square(n) + ".")
 | 
|  |     80 | 
 | 
|  |     81 | println(s"The square of ${n} is ${square(n)}.")
 | 
|  |     82 | 
 | 
|  |     83 | 
 | 
|  |     84 | // helpful for debugging purposes
 | 
|  |     85 | //
 | 
|  |     86 | //         "The most effective debugging tool is still careful thought, 
 | 
|  |     87 | //          coupled with judiciously placed print statements."
 | 
|  |     88 | //                   — Brian W. Kernighan, in Unix for Beginners (1979)
 | 
|  |     89 | 
 | 
|  |     90 | 
 | 
|  |     91 | def gcd_db(a: Int, b: Int) : Int = {
 | 
|  |     92 |   println(s"Function called with ${a} and ${b}.")
 | 
|  |     93 |   if (b == 0) a else gcd_db(b, a % b)
 | 
|  |     94 | }
 | 
|  |     95 | 
 | 
|  |     96 | gcd_db(48, 18)
 | 
|  |     97 | 
 | 
|  |     98 | 
 | 
|  |     99 | // Asserts/Testing
 | 
|  |    100 | //=================
 | 
|  |    101 | 
 | 
|  |    102 | assert(gcd(48, 18) == 6)
 | 
|  |    103 | 
 | 
|  |    104 | assert(gcd(48, 18) == 5, "The gcd test failed")
 | 
|  |    105 | 
 | 
|  |    106 | 
 | 
| 204 |    107 | 
 | 
|  |    108 | // Higher-Order Functions
 | 
|  |    109 | //========================
 | 
|  |    110 | 
 | 
|  |    111 | // functions can take functions as arguments
 | 
|  |    112 | 
 | 
|  |    113 | def even(x: Int) : Boolean = x % 2 == 0
 | 
|  |    114 | def odd(x: Int) : Boolean = x % 2 == 1
 | 
|  |    115 | 
 | 
|  |    116 | val lst = (1 to 10).toList
 | 
|  |    117 | 
 | 
|  |    118 | lst.filter(x => even(x))
 | 
|  |    119 | lst.filter(even(_))
 | 
|  |    120 | lst.filter(even)
 | 
|  |    121 | 
 | 
|  |    122 | lst.count(even)
 | 
|  |    123 | 
 | 
| 212 |    124 | 
 | 
|  |    125 | lst.find(even)
 | 
|  |    126 | 
 | 
|  |    127 | val ps = List((3, 0), (3, 2), (4, 2), (2, 2), (2, 0), (1, 1), (1, 0))
 | 
| 204 |    128 | 
 | 
| 212 |    129 | lst.sortWith(_ > _)
 | 
|  |    130 | lst.sortWith(_ < _)
 | 
| 204 |    131 | 
 | 
| 212 |    132 | def lex(x: (Int, Int), y: (Int, Int)) : Boolean = 
 | 
|  |    133 |   if (x._1 == y._1) x._2 < y._2 else x._1 < y._1
 | 
|  |    134 | 
 | 
|  |    135 | ps.sortWith(lex)
 | 
| 204 |    136 | 
 | 
|  |    137 | ps.sortBy(_._1)
 | 
|  |    138 | ps.sortBy(_._2)
 | 
|  |    139 | 
 | 
|  |    140 | ps.maxBy(_._1)
 | 
|  |    141 | ps.maxBy(_._2)
 | 
|  |    142 | 
 | 
|  |    143 | 
 | 
|  |    144 | 
 | 
| 212 |    145 | // maps (lower-case)
 | 
|  |    146 | //===================
 | 
| 204 |    147 | 
 | 
| 212 |    148 | def double(x: Int): Int = x + x
 | 
| 204 |    149 | def square(x: Int): Int = x * x
 | 
|  |    150 | 
 | 
| 212 |    151 | 
 | 
|  |    152 | 
 | 
| 204 |    153 | val lst = (1 to 10).toList
 | 
|  |    154 | 
 | 
| 212 |    155 | lst.map(x => (double(x), square(x)))
 | 
|  |    156 | 
 | 
| 204 |    157 | lst.map(square)
 | 
|  |    158 | 
 | 
| 268 |    159 | // this is actually how for-comprehensions 
 | 
|  |    160 | // defined as in Scala
 | 
| 204 |    161 | 
 | 
|  |    162 | lst.map(n => square(n))
 | 
|  |    163 | for (n <- lst) yield square(n)
 | 
|  |    164 | 
 | 
|  |    165 | // this can be iterated
 | 
|  |    166 | 
 | 
|  |    167 | lst.map(square).filter(_ > 4)
 | 
|  |    168 | 
 | 
|  |    169 | lst.map(square).filter(_ > 4).map(square)
 | 
|  |    170 | 
 | 
|  |    171 | 
 | 
|  |    172 | // lets define our own functions
 | 
|  |    173 | // type of functions, for example f: Int => Int
 | 
|  |    174 | 
 | 
| 212 |    175 | lst.tail
 | 
|  |    176 | 
 | 
| 204 |    177 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = {
 | 
|  |    178 |   if (lst == Nil) Nil
 | 
|  |    179 |   else f(lst.head) :: my_map_int(lst.tail, f)
 | 
|  |    180 | }
 | 
|  |    181 | 
 | 
|  |    182 | my_map_int(lst, square)
 | 
|  |    183 | 
 | 
|  |    184 | 
 | 
|  |    185 | // same function using pattern matching: a kind
 | 
|  |    186 | // of switch statement on steroids (see more later on)
 | 
|  |    187 | 
 | 
|  |    188 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = lst match {
 | 
|  |    189 |   case Nil => Nil
 | 
|  |    190 |   case x::xs => f(x)::my_map_int(xs, f)
 | 
|  |    191 | }
 | 
|  |    192 | 
 | 
|  |    193 | 
 | 
|  |    194 | // other function types
 | 
|  |    195 | //
 | 
|  |    196 | // f1: (Int, Int) => Int
 | 
|  |    197 | // f2: List[String] => Option[Int]
 | 
|  |    198 | // ... 
 | 
| 212 |    199 | val lst = (1 to 10).toList
 | 
| 204 |    200 | 
 | 
|  |    201 | def sumOf(f: Int => Int, lst: List[Int]): Int = lst match {
 | 
|  |    202 |   case Nil => 0
 | 
|  |    203 |   case x::xs => f(x) + sumOf(f, xs)
 | 
|  |    204 | }
 | 
|  |    205 | 
 | 
|  |    206 | def sum_squares(lst: List[Int]) = sumOf(square, lst)
 | 
|  |    207 | def sum_cubes(lst: List[Int])   = sumOf(x => x * x * x, lst)
 | 
|  |    208 | 
 | 
|  |    209 | sum_squares(lst)
 | 
|  |    210 | sum_cubes(lst)
 | 
|  |    211 | 
 | 
|  |    212 | // lets try it factorial
 | 
| 212 |    213 | def fact(n: Int) : Int = 
 | 
|  |    214 |   if (n == 0) 1 else n * fact(n - 1)
 | 
| 204 |    215 | 
 | 
|  |    216 | def sum_fact(lst: List[Int]) = sumOf(fact, lst)
 | 
|  |    217 | sum_fact(lst)
 | 
|  |    218 | 
 | 
|  |    219 | 
 | 
|  |    220 | 
 | 
|  |    221 | 
 | 
|  |    222 | 
 | 
| 212 |    223 | // Map type (upper-case)
 | 
|  |    224 | //=======================
 | 
| 204 |    225 | 
 | 
|  |    226 | // Note the difference between map and Map
 | 
|  |    227 | 
 | 
|  |    228 | def factors(n: Int) : List[Int] =
 | 
|  |    229 |   ((1 until n).filter { divisor =>
 | 
|  |    230 |       n % divisor == 0
 | 
|  |    231 |     }).toList
 | 
|  |    232 | 
 | 
|  |    233 | 
 | 
|  |    234 | var ls = (1 to 10).toList
 | 
|  |    235 | 
 | 
|  |    236 | val facs = ls.map(n => (n, factors(n)))
 | 
|  |    237 | 
 | 
|  |    238 | facs.find(_._1 == 4)
 | 
|  |    239 | 
 | 
|  |    240 | // works for lists of pairs
 | 
|  |    241 | facs.toMap
 | 
|  |    242 | 
 | 
|  |    243 | 
 | 
|  |    244 | facs.toMap.get(4)
 | 
| 212 |    245 | facs.toMap.getOrElse(42, Nil)
 | 
| 204 |    246 | 
 | 
|  |    247 | val facsMap = facs.toMap
 | 
|  |    248 | 
 | 
|  |    249 | val facsMap0 = facsMap + (0 -> List(1,2,3,4,5))
 | 
| 212 |    250 | facsMap0.get(1)
 | 
| 204 |    251 | 
 | 
|  |    252 | val facsMap4 = facsMap + (1 -> List(1,2,3,4,5))
 | 
|  |    253 | facsMap.get(1)
 | 
|  |    254 | facsMap4.get(1)
 | 
|  |    255 | 
 | 
|  |    256 | val ls = List("one", "two", "three", "four", "five")
 | 
|  |    257 | ls.groupBy(_.length)
 | 
|  |    258 | 
 | 
| 212 |    259 | ls.groupBy(_.length).get(2)
 | 
| 204 |    260 | 
 | 
|  |    261 | 
 | 
| 51 |    262 | 
 | 
| 268 |    263 | // Option type (again)
 | 
|  |    264 | //=====================
 | 
| 53 |    265 | 
 | 
| 268 |    266 | // remember, in Java if something unusually happens, 
 | 
|  |    267 | // you return null;
 | 
| 204 |    268 | //
 | 
| 268 |    269 | // in Scala you use Option
 | 
| 53 |    270 | //   - if the value is present, you use Some(value)
 | 
|  |    271 | //   - if no value is present, you use None
 | 
|  |    272 | 
 | 
|  |    273 | 
 | 
| 192 |    274 | List(7,2,3,4,5,6).find(_ < 4)
 | 
| 53 |    275 | List(5,6,7,8,9).find(_ < 4)
 | 
|  |    276 | 
 | 
| 204 |    277 | // operations on options
 | 
| 58 |    278 | 
 | 
| 51 |    279 | val lst = List(None, Some(1), Some(2), None, Some(3))
 | 
|  |    280 | 
 | 
|  |    281 | lst.flatten
 | 
| 53 |    282 | 
 | 
| 192 |    283 | Some(1).get
 | 
| 212 |    284 | None.get
 | 
| 51 |    285 | 
 | 
| 53 |    286 | Some(1).isDefined
 | 
|  |    287 | None.isDefined
 | 
|  |    288 | 
 | 
| 212 |    289 | 
 | 
|  |    290 | None.isDefined
 | 
|  |    291 | 
 | 
| 51 |    292 | val ps = List((3, 0), (3, 2), (4, 2), (2, 0), (1, 0), (1, 1))
 | 
|  |    293 | 
 | 
|  |    294 | for ((x, y) <- ps) yield {
 | 
|  |    295 |   if (y == 0) None else Some(x / y)
 | 
|  |    296 | }
 | 
|  |    297 | 
 | 
| 192 |    298 | // getOrElse is for setting a default value
 | 
| 53 |    299 | 
 | 
|  |    300 | val lst = List(None, Some(1), Some(2), None, Some(3))
 | 
| 204 |    301 | 
 | 
| 57 |    302 | for (x <- lst) yield x.getOrElse(0)
 | 
|  |    303 | 
 | 
|  |    304 | 
 | 
| 53 |    305 | 
 | 
|  |    306 | 
 | 
| 192 |    307 | // error handling with Option (no exceptions)
 | 
| 57 |    308 | //
 | 
|  |    309 | //  Try(something).getOrElse(what_to_do_in_an_exception)
 | 
|  |    310 | //
 | 
| 53 |    311 | import scala.util._
 | 
|  |    312 | import io.Source
 | 
|  |    313 | 
 | 
| 212 |    314 | 
 | 
|  |    315 | Source.fromURL("""http://www.inf.ucl.ac.uk/staff/urbanc/""").mkString
 | 
| 53 |    316 | 
 | 
| 192 |    317 | Try(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString).getOrElse("")
 | 
| 53 |    318 | 
 | 
| 192 |    319 | Try(Some(Source.fromURL("""http://www.inf.kcl.ac.uk/staff/urbanc/""").mkString)).getOrElse(None)
 | 
| 53 |    320 | 
 | 
|  |    321 | 
 | 
| 204 |    322 | // a function that turns strings into numbers (similar to .toInt)
 | 
| 212 |    323 | Integer.parseInt("12u34")
 | 
| 204 |    324 | 
 | 
|  |    325 | 
 | 
|  |    326 | def get_me_an_int(s: String) : Option[Int] = 
 | 
| 53 |    327 |  Try(Some(Integer.parseInt(s))).getOrElse(None)
 | 
|  |    328 | 
 | 
| 204 |    329 | val lst = List("12345", "foo", "5432", "bar", "x21", "456")
 | 
| 53 |    330 | for (x <- lst) yield get_me_an_int(x)
 | 
|  |    331 | 
 | 
| 268 |    332 | // summing up all the numbers
 | 
| 204 |    333 | 
 | 
| 212 |    334 | lst.map(get_me_an_int).flatten.sum
 | 
| 204 |    335 | lst.map(get_me_an_int).flatten.sum
 | 
|  |    336 | 
 | 
|  |    337 | 
 | 
| 212 |    338 | lst.flatMap(get_me_an_int).map(_.toString)
 | 
| 53 |    339 | 
 | 
|  |    340 | 
 | 
|  |    341 | // This may not look any better than working with null in Java, but to
 | 
|  |    342 | // see the value, you have to put yourself in the shoes of the
 | 
|  |    343 | // consumer of the get_me_an_int function, and imagine you didn't
 | 
|  |    344 | // write that function.
 | 
|  |    345 | //
 | 
|  |    346 | // In Java, if you didn't write this function, you'd have to depend on
 | 
| 192 |    347 | // the Javadoc of the get_me_an_int. If you didn't look at the Javadoc, 
 | 
| 57 |    348 | // you might not know that get_me_an_int could return a null, and your 
 | 
|  |    349 | // code could potentially throw a NullPointerException.
 | 
| 53 |    350 | 
 | 
|  |    351 | 
 | 
| 192 |    352 | 
 | 
| 58 |    353 | // even Scala is not immune to problems like this:
 | 
|  |    354 | 
 | 
| 192 |    355 | List(5,6,7,8,9).indexOf(7)
 | 
| 204 |    356 | List(5,6,7,8,9).indexOf(10)
 | 
| 212 |    357 | List(5,6,7,8,9)(-1)
 | 
| 192 |    358 | 
 | 
|  |    359 | 
 | 
|  |    360 | 
 | 
|  |    361 | // Pattern Matching
 | 
|  |    362 | //==================
 | 
|  |    363 | 
 | 
|  |    364 | // A powerful tool which is supposed to come to Java in a few years
 | 
|  |    365 | // time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
 | 
|  |    366 | // has it for many years ;o)
 | 
|  |    367 | 
 | 
|  |    368 | // The general schema:
 | 
|  |    369 | //
 | 
|  |    370 | //    expression match {
 | 
|  |    371 | //       case pattern1 => expression1
 | 
|  |    372 | //       case pattern2 => expression2
 | 
|  |    373 | //       ...
 | 
|  |    374 | //       case patternN => expressionN
 | 
|  |    375 | //    }
 | 
|  |    376 | 
 | 
|  |    377 | 
 | 
|  |    378 | 
 | 
|  |    379 | 
 | 
| 204 |    380 | // remember?
 | 
| 192 |    381 | val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
 | 
|  |    382 | 
 | 
|  |    383 | 
 | 
| 212 |    384 | def my_flatten(xs: List[Option[Int]]): List[Int] = xs match {
 | 
|  |    385 |   case Nil => Nil 
 | 
|  |    386 |   case None::rest => my_flatten(rest)
 | 
|  |    387 |   case Some(v)::foo => {
 | 
|  |    388 |       v :: my_flatten(foo)
 | 
|  |    389 |   } 
 | 
| 192 |    390 | }
 | 
| 58 |    391 | 
 | 
|  |    392 | 
 | 
| 192 |    393 | // another example
 | 
|  |    394 | def get_me_a_string(n: Int): String = n match {
 | 
| 212 |    395 |   case 0 | 1 | 2 => "small"
 | 
|  |    396 |   case _ => "big"
 | 
| 192 |    397 | }
 | 
|  |    398 | 
 | 
|  |    399 | get_me_a_string(0)
 | 
|  |    400 | 
 | 
| 212 |    401 | 
 | 
| 192 |    402 | // you can also have cases combined
 | 
| 266 |    403 | def season(month: String) : String = month match {
 | 
| 192 |    404 |   case "March" | "April" | "May" => "It's spring"
 | 
|  |    405 |   case "June" | "July" | "August" => "It's summer"
 | 
|  |    406 |   case "September" | "October" | "November" => "It's autumn"
 | 
| 204 |    407 |   case "December" => "It's winter"
 | 
|  |    408 |   case "January" | "February" => "It's unfortunately winter"
 | 
| 192 |    409 | }
 | 
|  |    410 |  
 | 
|  |    411 | println(season("November"))
 | 
|  |    412 | 
 | 
|  |    413 | // What happens if no case matches?
 | 
| 212 |    414 | println(season("foobar"))
 | 
| 192 |    415 | 
 | 
|  |    416 | 
 | 
| 266 |    417 | // Days of the months
 | 
|  |    418 | def days(month: String) : Int = month match {
 | 
|  |    419 |   case "March" | "April" | "May" => 31
 | 
|  |    420 |   case "June" | "July" | "August" => 30
 | 
|  |    421 | }
 | 
|  |    422 | 
 | 
|  |    423 | 
 | 
|  |    424 | 
 | 
|  |    425 | 
 | 
| 204 |    426 | // Silly: fizz buzz
 | 
| 192 |    427 | def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
 | 
|  |    428 |   case (0, 0) => "fizz buzz"
 | 
|  |    429 |   case (0, _) => "fizz"
 | 
|  |    430 |   case (_, 0) => "buzz"
 | 
|  |    431 |   case _ => n.toString  
 | 
|  |    432 | }
 | 
|  |    433 | 
 | 
|  |    434 | for (n <- 0 to 20) 
 | 
|  |    435 |  println(fizz_buzz(n))
 | 
|  |    436 | 
 | 
|  |    437 | 
 | 
|  |    438 | // User-defined Datatypes
 | 
|  |    439 | //========================
 | 
|  |    440 | 
 | 
|  |    441 | 
 | 
| 204 |    442 | abstract class Colour
 | 
|  |    443 | case object Red extends Colour 
 | 
|  |    444 | case object Green extends Colour 
 | 
|  |    445 | case object Blue extends Colour
 | 
| 192 |    446 | 
 | 
| 204 |    447 | def fav_colour(c: Colour) : Boolean = c match {
 | 
|  |    448 |   case Red   => false
 | 
|  |    449 |   case Green => true
 | 
|  |    450 |   case Blue  => false 
 | 
| 173 |    451 | }
 | 
|  |    452 | 
 | 
| 204 |    453 | fav_colour(Green)
 | 
|  |    454 | 
 | 
| 192 |    455 | 
 | 
| 268 |    456 | // ... a tiny bit more useful: Roman Numerals
 | 
| 204 |    457 | 
 | 
|  |    458 | abstract class RomanDigit 
 | 
|  |    459 | case object I extends RomanDigit 
 | 
|  |    460 | case object V extends RomanDigit 
 | 
|  |    461 | case object X extends RomanDigit 
 | 
|  |    462 | case object L extends RomanDigit 
 | 
|  |    463 | case object C extends RomanDigit 
 | 
|  |    464 | case object D extends RomanDigit 
 | 
|  |    465 | case object M extends RomanDigit 
 | 
|  |    466 | 
 | 
|  |    467 | type RomanNumeral = List[RomanDigit] 
 | 
| 192 |    468 | 
 | 
| 212 |    469 | List(X,I)
 | 
|  |    470 | 
 | 
| 268 |    471 | /*
 | 
| 212 |    472 | I -> 1
 | 
|  |    473 | II -> 2
 | 
|  |    474 | III  -> 3
 | 
|  |    475 | IV -> 4
 | 
|  |    476 | V -> 5
 | 
|  |    477 | VI -> 6
 | 
|  |    478 | VII -> 7
 | 
|  |    479 | VIII -> 8
 | 
|  |    480 | IX -> 9
 | 
|  |    481 | X -> X
 | 
| 268 |    482 | */
 | 
| 212 |    483 | 
 | 
| 204 |    484 | def RomanNumeral2Int(rs: RomanNumeral): Int = rs match { 
 | 
|  |    485 |   case Nil => 0
 | 
|  |    486 |   case M::r    => 1000 + RomanNumeral2Int(r)  
 | 
|  |    487 |   case C::M::r => 900 + RomanNumeral2Int(r)
 | 
|  |    488 |   case D::r    => 500 + RomanNumeral2Int(r)
 | 
|  |    489 |   case C::D::r => 400 + RomanNumeral2Int(r)
 | 
|  |    490 |   case C::r    => 100 + RomanNumeral2Int(r)
 | 
|  |    491 |   case X::C::r => 90 + RomanNumeral2Int(r)
 | 
|  |    492 |   case L::r    => 50 + RomanNumeral2Int(r)
 | 
|  |    493 |   case X::L::r => 40 + RomanNumeral2Int(r)
 | 
|  |    494 |   case X::r    => 10 + RomanNumeral2Int(r)
 | 
|  |    495 |   case I::X::r => 9 + RomanNumeral2Int(r)
 | 
|  |    496 |   case V::r    => 5 + RomanNumeral2Int(r)
 | 
|  |    497 |   case I::V::r => 4 + RomanNumeral2Int(r)
 | 
|  |    498 |   case I::r    => 1 + RomanNumeral2Int(r)
 | 
| 192 |    499 | }
 | 
|  |    500 | 
 | 
| 204 |    501 | RomanNumeral2Int(List(I,V))             // 4
 | 
|  |    502 | RomanNumeral2Int(List(I,I,I,I))         // 4 (invalid Roman number)
 | 
|  |    503 | RomanNumeral2Int(List(V,I))             // 6
 | 
|  |    504 | RomanNumeral2Int(List(I,X))             // 9
 | 
|  |    505 | RomanNumeral2Int(List(M,C,M,L,X,X,I,X)) // 1979
 | 
|  |    506 | RomanNumeral2Int(List(M,M,X,V,I,I))     // 2017
 | 
|  |    507 | 
 | 
| 192 |    508 | 
 | 
| 204 |    509 | // another example
 | 
|  |    510 | //=================
 | 
| 192 |    511 | 
 | 
| 212 |    512 | // Once upon a time, in a complete fictional 
 | 
|  |    513 | // country there were Persons...
 | 
| 192 |    514 | 
 | 
|  |    515 | 
 | 
|  |    516 | abstract class Person
 | 
| 204 |    517 | case object King extends Person
 | 
| 192 |    518 | case class Peer(deg: String, terr: String, succ: Int) extends Person
 | 
|  |    519 | case class Knight(name: String) extends Person
 | 
|  |    520 | case class Peasant(name: String) extends Person
 | 
| 212 |    521 | 
 | 
| 173 |    522 | 
 | 
| 192 |    523 | def title(p: Person): String = p match {
 | 
| 204 |    524 |   case King => "His Majesty the King"
 | 
| 192 |    525 |   case Peer(deg, terr, _) => s"The ${deg} of ${terr}"
 | 
|  |    526 |   case Knight(name) => s"Sir ${name}"
 | 
|  |    527 |   case Peasant(name) => name
 | 
|  |    528 | }
 | 
| 173 |    529 | 
 | 
| 192 |    530 | def superior(p1: Person, p2: Person): Boolean = (p1, p2) match {
 | 
| 204 |    531 |   case (King, _) => true
 | 
| 192 |    532 |   case (Peer(_,_,_), Knight(_)) => true
 | 
|  |    533 |   case (Peer(_,_,_), Peasant(_)) => true
 | 
| 204 |    534 |   case (Peer(_,_,_), Clown) => true
 | 
| 192 |    535 |   case (Knight(_), Peasant(_)) => true
 | 
| 204 |    536 |   case (Knight(_), Clown) => true
 | 
|  |    537 |   case (Clown, Peasant(_)) => true
 | 
| 192 |    538 |   case _ => false
 | 
|  |    539 | }
 | 
|  |    540 | 
 | 
|  |    541 | val people = List(Knight("David"), 
 | 
|  |    542 |                   Peer("Duke", "Norfolk", 84), 
 | 
|  |    543 |                   Peasant("Christian"), 
 | 
| 204 |    544 |                   King, 
 | 
|  |    545 |                   Clown)
 | 
| 192 |    546 | 
 | 
| 212 |    547 | println(people.sortWith(superior).mkString("\n"))
 | 
|  |    548 | 
 | 
| 192 |    549 | 
 | 
| 278 |    550 | // String interpolations as patterns
 | 
|  |    551 | 
 | 
|  |    552 | val date = "2000-01-01"
 | 
|  |    553 | val s"$year-$month-$day" = date
 | 
|  |    554 | 
 | 
|  |    555 | def parse_date(date: String) = date match {
 | 
|  |    556 |   case s"$year-$month-$day" => Some((year.toInt, month.toInt, day.toInt))
 | 
|  |    557 |   case s"$day/$month/$year" => Some((year.toInt, month.toInt, day.toInt))
 | 
|  |    558 |   case _ => None
 | 
|  |    559 | } 
 | 
|  |    560 | 
 | 
|  |    561 | 
 | 
| 309 |    562 | // Recursion
 | 
|  |    563 | //===========
 | 
|  |    564 | 
 | 
|  |    565 | /* a, b, c
 | 
|  |    566 | 
 | 
|  |    567 | aa         aaa
 | 
|  |    568 | ab         baa 
 | 
|  |    569 | ac         caa 
 | 
|  |    570 | ba  =>     ......
 | 
|  |    571 | bb
 | 
|  |    572 | bc
 | 
|  |    573 | ca
 | 
|  |    574 | cb
 | 
|  |    575 | cc
 | 
|  |    576 | 
 | 
|  |    577 | */
 | 
|  |    578 | 
 | 
|  |    579 | def perms(cs: List[Char], l: Int) : List[String] = {
 | 
|  |    580 |   if (l == 0) List("")
 | 
|  |    581 |   else for (c <- cs; s <- perms(cs, l - 1)) yield s"$c$s"
 | 
|  |    582 | }
 | 
|  |    583 | 
 | 
|  |    584 | perms("abc".toList, 2)
 | 
|  |    585 | 
 | 
|  |    586 | def move(from: Char, to: Char) =
 | 
|  |    587 |   println(s"Move disc from $from to $to!")
 | 
|  |    588 | 
 | 
|  |    589 | def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
 | 
|  |    590 |   if (n == 0) ()
 | 
|  |    591 |   else {
 | 
|  |    592 |     hanoi(n - 1, from, to, via)
 | 
|  |    593 |     move(from, to)
 | 
|  |    594 |     hanoi(n - 1, via, from, to)
 | 
|  |    595 |   }
 | 
|  |    596 | } 
 | 
|  |    597 | 
 | 
|  |    598 | hanoi(40, 'A', 'B', 'C')
 | 
|  |    599 | 
 | 
|  |    600 | 
 | 
| 268 |    601 | // Tail Recursion
 | 
| 204 |    602 | //================
 | 
| 147 |    603 | 
 | 
|  |    604 | 
 | 
| 204 |    605 | def fact(n: Long): Long = 
 | 
|  |    606 |   if (n == 0) 1 else n * fact(n - 1)
 | 
| 147 |    607 | 
 | 
| 204 |    608 | fact(10)              //ok
 | 
|  |    609 | fact(10000)           // produces a stackoverflow
 | 
| 147 |    610 | 
 | 
| 204 |    611 | def factT(n: BigInt, acc: BigInt): BigInt =
 | 
|  |    612 |   if (n == 0) acc else factT(n - 1, n * acc)
 | 
| 147 |    613 | 
 | 
| 204 |    614 | factT(10, 1)
 | 
|  |    615 | factT(100000, 1)
 | 
| 192 |    616 | 
 | 
| 204 |    617 | // there is a flag for ensuring a function is tail recursive
 | 
|  |    618 | import scala.annotation.tailrec
 | 
| 167 |    619 | 
 | 
| 204 |    620 | @tailrec
 | 
|  |    621 | def factT(n: BigInt, acc: BigInt): BigInt =
 | 
|  |    622 |   if (n == 0) acc else factT(n - 1, n * acc)
 | 
| 167 |    623 | 
 | 
|  |    624 | 
 | 
|  |    625 | 
 | 
| 204 |    626 | // for tail-recursive functions the Scala compiler
 | 
|  |    627 | // generates loop-like code, which does not need
 | 
|  |    628 | // to allocate stack-space in each recursive
 | 
|  |    629 | // call; Scala can do this only for tail-recursive
 | 
|  |    630 | // functions
 | 
|  |    631 | 
 | 
| 147 |    632 | 
 | 
| 212 |    633 | // A Web Crawler / Email Harvester
 | 
|  |    634 | //=================================
 | 
| 204 |    635 | //
 | 
| 212 |    636 | // the idea is to look for links using the
 | 
|  |    637 | // regular expression "https?://[^"]*" and for
 | 
|  |    638 | // email addresses using another regex.
 | 
| 204 |    639 | 
 | 
|  |    640 | import io.Source
 | 
|  |    641 | import scala.util._
 | 
|  |    642 | 
 | 
|  |    643 | // gets the first 10K of a web-page
 | 
|  |    644 | def get_page(url: String) : String = {
 | 
|  |    645 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | 
|  |    646 |     getOrElse { println(s"  Problem with: $url"); ""}
 | 
| 147 |    647 | }
 | 
|  |    648 | 
 | 
| 204 |    649 | // regex for URLs and emails
 | 
|  |    650 | val http_pattern = """"https?://[^"]*"""".r
 | 
|  |    651 | val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
 | 
|  |    652 | 
 | 
| 268 |    653 | //test case:
 | 
| 212 |    654 | //email_pattern.findAllIn
 | 
|  |    655 | //  ("foo bla christian@kcl.ac.uk 1234567").toList
 | 
|  |    656 | 
 | 
| 204 |    657 | 
 | 
|  |    658 | // drops the first and last character from a string
 | 
|  |    659 | def unquote(s: String) = s.drop(1).dropRight(1)
 | 
|  |    660 | 
 | 
|  |    661 | def get_all_URLs(page: String): Set[String] = 
 | 
|  |    662 |   http_pattern.findAllIn(page).map(unquote).toSet
 | 
|  |    663 | 
 | 
|  |    664 | // naive version of crawl - searches until a given depth,
 | 
|  |    665 | // visits pages potentially more than once
 | 
|  |    666 | def crawl(url: String, n: Int) : Set[String] = {
 | 
|  |    667 |   if (n == 0) Set()
 | 
|  |    668 |   else {
 | 
|  |    669 |     println(s"  Visiting: $n $url")
 | 
|  |    670 |     val page = get_page(url)
 | 
|  |    671 |     val new_emails = email_pattern.findAllIn(page).toSet
 | 
| 212 |    672 |     new_emails ++ (for (u <- get_all_URLs(page)) yield crawl(u, n - 1)).flatten
 | 
| 204 |    673 |   }
 | 
| 147 |    674 | }
 | 
|  |    675 | 
 | 
| 204 |    676 | // some starting URLs for the crawler
 | 
|  |    677 | val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
 | 
| 147 |    678 | 
 | 
| 204 |    679 | crawl(startURL, 2)
 | 
|  |    680 | 
 | 
|  |    681 | 
 | 
|  |    682 | 
 | 
|  |    683 | 
 | 
| 150 |    684 | 
 | 
|  |    685 | 
 | 
|  |    686 | 
 | 
| 192 |    687 | // Sudoku
 | 
|  |    688 | //========
 | 
| 53 |    689 | 
 | 
| 57 |    690 | // THE POINT OF THIS CODE IS NOT TO BE SUPER
 | 
|  |    691 | // EFFICIENT AND FAST, just explaining exhaustive
 | 
|  |    692 | // depth-first search
 | 
|  |    693 | 
 | 
|  |    694 | 
 | 
| 55 |    695 | val game0 = """.14.6.3..
 | 
|  |    696 |               |62...4..9
 | 
|  |    697 |               |.8..5.6..
 | 
|  |    698 |               |.6.2....3
 | 
|  |    699 |               |.7..1..5.
 | 
|  |    700 |               |5....9.6.
 | 
|  |    701 |               |..6.2..3.
 | 
|  |    702 |               |1..5...92
 | 
|  |    703 |               |..7.9.41.""".stripMargin.replaceAll("\\n", "")
 | 
|  |    704 | 
 | 
|  |    705 | type Pos = (Int, Int)
 | 
| 268 |    706 | val emptyValue = '.'
 | 
|  |    707 | val maxValue = 9
 | 
| 55 |    708 | 
 | 
|  |    709 | val allValues = "123456789".toList
 | 
|  |    710 | val indexes = (0 to 8).toList
 | 
|  |    711 | 
 | 
| 57 |    712 | 
 | 
| 268 |    713 | def empty(game: String) = game.indexOf(emptyValue)
 | 
|  |    714 | def isDone(game: String) = empty(game) == -1 
 | 
|  |    715 | def emptyPosition(game: String) : Pos = 
 | 
|  |    716 |   (empty(game) % maxValue, empty(game) / maxValue)
 | 
| 57 |    717 | 
 | 
| 55 |    718 | 
 | 
| 268 |    719 | def get_row(game: String, y: Int) = indexes.map(col => game(y * maxValue + col))
 | 
|  |    720 | def get_col(game: String, x: Int) = indexes.map(row => game(x + row * maxValue))
 | 
| 147 |    721 | 
 | 
| 57 |    722 | def get_box(game: String, pos: Pos): List[Char] = {
 | 
| 55 |    723 |     def base(p: Int): Int = (p / 3) * 3
 | 
|  |    724 |     val x0 = base(pos._1)
 | 
|  |    725 |     val y0 = base(pos._2)
 | 
| 268 |    726 |     for (x <- (x0 until x0 + 3).toList;
 | 
|  |    727 |          y <- (y0 until y0 + 3).toList) yield game(x + y * maxValue)
 | 
|  |    728 | }         
 | 
| 55 |    729 | 
 | 
|  |    730 | 
 | 
| 192 |    731 | //get_row(game0, 0)
 | 
|  |    732 | //get_row(game0, 1)
 | 
|  |    733 | //get_box(game0, (3,1))
 | 
|  |    734 | 
 | 
| 268 |    735 | def update(game: String, pos: Int, value: Char): String = 
 | 
|  |    736 |   game.updated(pos, value)
 | 
| 55 |    737 | 
 | 
|  |    738 | def toAvoid(game: String, pos: Pos): List[Char] = 
 | 
| 57 |    739 |   (get_col(game, pos._1) ++ get_row(game, pos._2) ++ get_box(game, pos))
 | 
| 55 |    740 | 
 | 
| 268 |    741 | def candidates(game: String, pos: Pos): List[Char] = 
 | 
|  |    742 |   allValues.diff(toAvoid(game, pos))
 | 
| 55 |    743 | 
 | 
| 268 |    744 | //candidates(game0, (0, 0))
 | 
| 55 |    745 | 
 | 
| 268 |    746 | def pretty(game: String): String = 
 | 
|  |    747 |   "\n" ++ (game.sliding(maxValue, maxValue).mkString("\n"))
 | 
| 55 |    748 | 
 | 
|  |    749 | def search(game: String): List[String] = {
 | 
|  |    750 |   if (isDone(game)) List(game)
 | 
| 192 |    751 |   else 
 | 
| 268 |    752 |     candidates(game, emptyPosition(game)).
 | 
|  |    753 |       map(c => search(update(game, empty(game), c))).flatten
 | 
| 55 |    754 | }
 | 
|  |    755 | 
 | 
| 268 |    756 | // an easy game
 | 
| 55 |    757 | val game1 = """23.915...
 | 
|  |    758 |               |...2..54.
 | 
|  |    759 |               |6.7......
 | 
|  |    760 |               |..1.....9
 | 
|  |    761 |               |89.5.3.17
 | 
|  |    762 |               |5.....6..
 | 
|  |    763 |               |......9.5
 | 
|  |    764 |               |.16..7...
 | 
|  |    765 |               |...329..1""".stripMargin.replaceAll("\\n", "")
 | 
|  |    766 | 
 | 
| 57 |    767 | 
 | 
| 268 |    768 | // a game that is in the sligtly harder category
 | 
| 55 |    769 | val game2 = """8........
 | 
|  |    770 |               |..36.....
 | 
|  |    771 |               |.7..9.2..
 | 
|  |    772 |               |.5...7...
 | 
|  |    773 |               |....457..
 | 
|  |    774 |               |...1...3.
 | 
|  |    775 |               |..1....68
 | 
|  |    776 |               |..85...1.
 | 
|  |    777 |               |.9....4..""".stripMargin.replaceAll("\\n", "")
 | 
|  |    778 | 
 | 
| 268 |    779 | // a game with multiple solutions
 | 
| 55 |    780 | val game3 = """.8...9743
 | 
|  |    781 |               |.5...8.1.
 | 
|  |    782 |               |.1.......
 | 
|  |    783 |               |8....5...
 | 
|  |    784 |               |...8.4...
 | 
|  |    785 |               |...3....6
 | 
|  |    786 |               |.......7.
 | 
|  |    787 |               |.3.5...8.
 | 
|  |    788 |               |9724...5.""".stripMargin.replaceAll("\\n", "")
 | 
|  |    789 | 
 | 
| 57 |    790 | 
 | 
| 192 |    791 | search(game0).map(pretty)
 | 
|  |    792 | search(game1).map(pretty)
 | 
| 55 |    793 | 
 | 
|  |    794 | // for measuring time
 | 
|  |    795 | def time_needed[T](i: Int, code: => T) = {
 | 
|  |    796 |   val start = System.nanoTime()
 | 
|  |    797 |   for (j <- 1 to i) code
 | 
|  |    798 |   val end = System.nanoTime()
 | 
| 268 |    799 |   s"${(end - start) / i / 1.0e9} secs"
 | 
| 55 |    800 | }
 | 
|  |    801 | 
 | 
|  |    802 | search(game2).map(pretty)
 | 
| 57 |    803 | search(game3).distinct.length
 | 
| 192 |    804 | time_needed(3, search(game2))
 | 
|  |    805 | time_needed(3, search(game3))
 | 
| 55 |    806 | 
 | 
| 53 |    807 | 
 | 
|  |    808 | 
 | 
|  |    809 | 
 | 
| 192 |    810 | 
 | 
| 278 |    811 | // if you like verbosity, you can full-specify the literal. 
 | 
|  |    812 | // Don't go telling that to people, though
 | 
|  |    813 | (1 to 100).filter((x: Int) => x % 2 == 0).sum 
 | 
|  |    814 | 
 | 
|  |    815 | // As x is known to be an Int anyway, you can omit that part
 | 
|  |    816 | (1 to 100).filter(x => x % 2 == 0).sum
 | 
|  |    817 | 
 | 
|  |    818 | // As each parameter (only x in this case) is passed only once
 | 
|  |    819 | // you can use the wizardy placeholder syntax
 | 
|  |    820 | (1 to 100).filter(_ % 2 == 0).sum
 | 
|  |    821 | 
 | 
|  |    822 | // But if you want to re-use your literal, you can also put it in a value
 | 
|  |    823 | // In this case, explicit types are required because there's nothing to infer from
 | 
|  |    824 | val isEven: (x: Int) => x % 2 == 0
 | 
|  |    825 | (1 to 100).filter(isEven).sum
 |