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