| 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 | 
 | 
| 318 |     17 | def cube(n: Int) : Int = n * n * n
 | 
|  |     18 | 
 | 
| 317 |     19 | val n = 3
 | 
| 318 |     20 | println("The cube of " + n + " is " + cube(n) + ".")
 | 
| 317 |     21 | 
 | 
| 318 |     22 | println(s"The cube of ${n} is ${cube(n)}.")
 | 
| 317 |     23 | 
 | 
| 318 |     24 | // or even
 | 
|  |     25 | 
 | 
|  |     26 | println(s"The cube of ${n} is ${n * n * n}.")
 | 
| 317 |     27 | 
 | 
|  |     28 | // helpful for debugging purposes
 | 
|  |     29 | //
 | 
|  |     30 | //         "The most effective debugging tool is still careful thought, 
 | 
|  |     31 | //          coupled with judiciously placed print statements."
 | 
|  |     32 | //                   — Brian W. Kernighan, in Unix for Beginners (1979)
 | 
|  |     33 | 
 | 
|  |     34 | 
 | 
|  |     35 | def gcd_db(a: Int, b: Int) : Int = {
 | 
|  |     36 |   println(s"Function called with ${a} and ${b}.")
 | 
|  |     37 |   if (b == 0) a else gcd_db(b, a % b)
 | 
|  |     38 | }
 | 
|  |     39 | 
 | 
|  |     40 | gcd_db(48, 18)
 | 
| 204 |     41 | 
 | 
|  |     42 | 
 | 
| 316 |     43 | // The Option Type
 | 
|  |     44 | //=================
 | 
|  |     45 | 
 | 
|  |     46 | // in Java, if something unusually happens, you return null or 
 | 
|  |     47 | // raise an exception
 | 
|  |     48 | //
 | 
|  |     49 | //in Scala you use Options instead
 | 
|  |     50 | //   - if the value is present, you use Some(value)
 | 
|  |     51 | //   - if no value is present, you use None
 | 
| 204 |     52 | 
 | 
|  |     53 | 
 | 
| 316 |     54 | List(7,2,3,4,5,6).find(_ < 4)
 | 
|  |     55 | List(5,6,7,8,9).find(_ < 4)
 | 
| 212 |     56 | 
 | 
| 310 |     57 | 
 | 
| 316 |     58 | // better error handling with Options (no exceptions)
 | 
|  |     59 | //
 | 
|  |     60 | //  Try(something).getOrElse(what_to_do_in_case_of_an_exception)
 | 
| 204 |     61 | //
 | 
| 316 |     62 | 
 | 
|  |     63 | import scala.util._
 | 
|  |     64 | import io.Source
 | 
|  |     65 | 
 | 
|  |     66 | val my_url = "https://nms.kcl.ac.uk/christian.urban/"
 | 
|  |     67 | 
 | 
|  |     68 | Source.fromURL(my_url).mkString
 | 
|  |     69 | 
 | 
|  |     70 | Try(Source.fromURL(my_url).mkString).getOrElse("")
 | 
|  |     71 | 
 | 
|  |     72 | Try(Some(Source.fromURL(my_url).mkString)).getOrElse(None)
 | 
| 204 |     73 | 
 | 
|  |     74 | 
 | 
| 316 |     75 | // the same for files
 | 
|  |     76 | Try(Some(Source.fromFile("text.txt").mkString)).getOrElse(None)
 | 
|  |     77 | 
 | 
| 204 |     78 | 
 | 
| 319 |     79 | // how to implement a function for reading 
 | 
|  |     80 | // (lines) something from files...
 | 
|  |     81 | //
 | 
| 316 |     82 | def get_contents(name: String) : List[String] = 
 | 
|  |     83 |   Source.fromFile(name).getLines.toList
 | 
| 204 |     84 | 
 | 
| 319 |     85 | get_contents("text.txt")
 | 
| 316 |     86 | get_contents("test.txt")
 | 
| 204 |     87 | 
 | 
| 316 |     88 | // slightly better - return Nil
 | 
|  |     89 | def get_contents(name: String) : List[String] = 
 | 
|  |     90 |   Try(Source.fromFile(name).getLines.toList).getOrElse(List())
 | 
| 204 |     91 | 
 | 
| 316 |     92 | get_contents("text.txt")
 | 
| 204 |     93 | 
 | 
| 316 |     94 | // much better - you record in the type that things can go wrong 
 | 
|  |     95 | def get_contents(name: String) : Option[List[String]] = 
 | 
|  |     96 |   Try(Some(Source.fromFile(name).getLines.toList)).getOrElse(None)
 | 
| 204 |     97 | 
 | 
| 316 |     98 | get_contents("text.txt")
 | 
|  |     99 | get_contents("test.txt")
 | 
| 204 |    100 | 
 | 
|  |    101 | 
 | 
| 317 |    102 | // operations on options
 | 
| 204 |    103 | 
 | 
| 317 |    104 | val lst = List(None, Some(1), Some(2), None, Some(3))
 | 
| 204 |    105 | 
 | 
| 317 |    106 | lst.flatten
 | 
| 204 |    107 | 
 | 
| 317 |    108 | Some(1).get
 | 
|  |    109 | None.get
 | 
| 310 |    110 | 
 | 
| 317 |    111 | Some(1).isDefined
 | 
|  |    112 | None.isDefined
 | 
| 310 |    113 | 
 | 
|  |    114 | 
 | 
| 318 |    115 | val ps = List((3, 0), (4, 2), (6, 2), (2, 0), (1, 0), (1, 1))
 | 
| 317 |    116 | 
 | 
|  |    117 | // division where possible
 | 
|  |    118 | 
 | 
|  |    119 | for ((x, y) <- ps) yield {
 | 
|  |    120 |   if (y == 0) None else Some(x / y)
 | 
|  |    121 | }
 | 
|  |    122 | 
 | 
|  |    123 | // getOrElse is for setting a default value
 | 
|  |    124 | 
 | 
|  |    125 | val lst = List(None, Some(1), Some(2), None, Some(3))
 | 
|  |    126 | 
 | 
|  |    127 | for (x <- lst) yield x.getOrElse(0)
 | 
|  |    128 | 
 | 
|  |    129 | 
 | 
| 318 |    130 | // a function that turns strings into numbers (similar to .toInt)
 | 
|  |    131 | Integer.parseInt("1234")
 | 
|  |    132 | 
 | 
|  |    133 | 
 | 
|  |    134 | def get_me_an_int(s: String) : Option[Int] = 
 | 
|  |    135 |  Try(Some(Integer.parseInt(s))).getOrElse(None)
 | 
| 310 |    136 | 
 | 
|  |    137 | 
 | 
| 317 |    138 | // This may not look any better than working with null in Java, but to
 | 
|  |    139 | // see the value, you have to put yourself in the shoes of the
 | 
|  |    140 | // consumer of the get_me_an_int function, and imagine you didn't
 | 
|  |    141 | // write that function.
 | 
|  |    142 | //
 | 
|  |    143 | // In Java, if you didn't write this function, you'd have to depend on
 | 
|  |    144 | // the Javadoc of the get_me_an_int. If you didn't look at the Javadoc, 
 | 
| 318 |    145 | // you might not know that get_me_an_int could return null, and your 
 | 
| 317 |    146 | // code could potentially throw a NullPointerException.
 | 
| 310 |    147 | 
 | 
|  |    148 | 
 | 
| 317 |    149 | // even Scala is not immune to problems like this:
 | 
| 310 |    150 | 
 | 
| 317 |    151 | List(5,6,7,8,9).indexOf(7)
 | 
|  |    152 | List(5,6,7,8,9).indexOf(10)
 | 
|  |    153 | List(5,6,7,8,9)(-1)
 | 
| 310 |    154 | 
 | 
|  |    155 | 
 | 
|  |    156 | 
 | 
| 204 |    157 | 
 | 
|  |    158 | // Higher-Order Functions
 | 
|  |    159 | //========================
 | 
|  |    160 | 
 | 
|  |    161 | // functions can take functions as arguments
 | 
| 319 |    162 | // and produce functions as result
 | 
| 204 |    163 | 
 | 
|  |    164 | def even(x: Int) : Boolean = x % 2 == 0
 | 
|  |    165 | def odd(x: Int) : Boolean = x % 2 == 1
 | 
|  |    166 | 
 | 
|  |    167 | val lst = (1 to 10).toList
 | 
|  |    168 | 
 | 
|  |    169 | lst.filter(even)
 | 
|  |    170 | lst.count(even)
 | 
| 212 |    171 | lst.find(even)
 | 
|  |    172 | 
 | 
| 318 |    173 | lst.filter(x => x % 2 == 0)
 | 
|  |    174 | lst.filter(_ % 2 == 0)
 | 
| 204 |    175 | 
 | 
| 212 |    176 | lst.sortWith(_ > _)
 | 
|  |    177 | lst.sortWith(_ < _)
 | 
| 204 |    178 | 
 | 
| 318 |    179 | // but this only works when the arguments are clear, but 
 | 
|  |    180 | // not with multiple occurences
 | 
|  |    181 | lst.find(n => odd(n) && n > 2)
 | 
|  |    182 | 
 | 
|  |    183 | 
 | 
|  |    184 | val ps = List((3, 0), (3, 2), (4, 2), (2, 2), (2, 0), (1, 1), (1, 0))
 | 
|  |    185 | 
 | 
| 212 |    186 | def lex(x: (Int, Int), y: (Int, Int)) : Boolean = 
 | 
|  |    187 |   if (x._1 == y._1) x._2 < y._2 else x._1 < y._1
 | 
|  |    188 | 
 | 
|  |    189 | ps.sortWith(lex)
 | 
| 204 |    190 | 
 | 
|  |    191 | ps.sortBy(_._1)
 | 
|  |    192 | ps.sortBy(_._2)
 | 
|  |    193 | 
 | 
|  |    194 | ps.maxBy(_._1)
 | 
|  |    195 | ps.maxBy(_._2)
 | 
|  |    196 | 
 | 
|  |    197 | 
 | 
| 212 |    198 | // maps (lower-case)
 | 
|  |    199 | //===================
 | 
| 204 |    200 | 
 | 
| 212 |    201 | def double(x: Int): Int = x + x
 | 
| 204 |    202 | def square(x: Int): Int = x * x
 | 
|  |    203 | 
 | 
| 212 |    204 | 
 | 
| 204 |    205 | val lst = (1 to 10).toList
 | 
|  |    206 | 
 | 
| 212 |    207 | lst.map(x => (double(x), square(x)))
 | 
|  |    208 | 
 | 
| 204 |    209 | lst.map(square)
 | 
|  |    210 | 
 | 
| 319 |    211 | // this is actually how for-comprehensions are
 | 
|  |    212 | // defined in Scala
 | 
| 204 |    213 | 
 | 
|  |    214 | lst.map(n => square(n))
 | 
|  |    215 | for (n <- lst) yield square(n)
 | 
|  |    216 | 
 | 
|  |    217 | // this can be iterated
 | 
|  |    218 | 
 | 
|  |    219 | lst.map(square).filter(_ > 4)
 | 
|  |    220 | 
 | 
|  |    221 | lst.map(square).filter(_ > 4).map(square)
 | 
|  |    222 | 
 | 
|  |    223 | 
 | 
| 318 |    224 | // lets define our own higher-order functions
 | 
|  |    225 | // type of functions is for example Int => Int
 | 
| 204 |    226 | 
 | 
| 212 |    227 | 
 | 
| 204 |    228 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = {
 | 
|  |    229 |   if (lst == Nil) Nil
 | 
|  |    230 |   else f(lst.head) :: my_map_int(lst.tail, f)
 | 
|  |    231 | }
 | 
|  |    232 | 
 | 
|  |    233 | my_map_int(lst, square)
 | 
|  |    234 | 
 | 
|  |    235 | 
 | 
|  |    236 | // same function using pattern matching: a kind
 | 
|  |    237 | // of switch statement on steroids (see more later on)
 | 
|  |    238 | 
 | 
| 319 |    239 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = 
 | 
|  |    240 | lst match {
 | 
| 204 |    241 |   case Nil => Nil
 | 
|  |    242 |   case x::xs => f(x)::my_map_int(xs, f)
 | 
|  |    243 | }
 | 
|  |    244 | 
 | 
|  |    245 | 
 | 
|  |    246 | // other function types
 | 
|  |    247 | //
 | 
|  |    248 | // f1: (Int, Int) => Int
 | 
|  |    249 | // f2: List[String] => Option[Int]
 | 
|  |    250 | // ... 
 | 
| 212 |    251 | val lst = (1 to 10).toList
 | 
| 204 |    252 | 
 | 
|  |    253 | def sumOf(f: Int => Int, lst: List[Int]): Int = lst match {
 | 
|  |    254 |   case Nil => 0
 | 
|  |    255 |   case x::xs => f(x) + sumOf(f, xs)
 | 
|  |    256 | }
 | 
|  |    257 | 
 | 
|  |    258 | def sum_squares(lst: List[Int]) = sumOf(square, lst)
 | 
|  |    259 | def sum_cubes(lst: List[Int])   = sumOf(x => x * x * x, lst)
 | 
|  |    260 | 
 | 
|  |    261 | sum_squares(lst)
 | 
|  |    262 | sum_cubes(lst)
 | 
|  |    263 | 
 | 
| 318 |    264 | // lets try a factorial
 | 
| 212 |    265 | def fact(n: Int) : Int = 
 | 
|  |    266 |   if (n == 0) 1 else n * fact(n - 1)
 | 
| 204 |    267 | 
 | 
|  |    268 | def sum_fact(lst: List[Int]) = sumOf(fact, lst)
 | 
|  |    269 | sum_fact(lst)
 | 
|  |    270 | 
 | 
|  |    271 | 
 | 
|  |    272 | 
 | 
| 318 |    273 | // sometimes it is needed that you specify the type. 
 | 
| 317 |    274 | (1 to 100).filter((x: Int) => x % 2 == 0).sum 
 | 
|  |    275 | 
 | 
| 319 |    276 | // in this case it is clear that x must be an Int
 | 
| 317 |    277 | (1 to 100).filter(x => x % 2 == 0).sum
 | 
|  |    278 | 
 | 
| 319 |    279 | // When each parameter (only x in this case) is used only once
 | 
| 317 |    280 | // you can use the wizardy placeholder syntax
 | 
|  |    281 | (1 to 100).filter(_ % 2 == 0).sum
 | 
|  |    282 | 
 | 
|  |    283 | 
 | 
|  |    284 | 
 | 
| 318 |    285 | // Option Type and maps
 | 
|  |    286 | //======================
 | 
| 317 |    287 | 
 | 
|  |    288 | // a function that turns strings into numbers (similar to .toInt)
 | 
|  |    289 | Integer.parseInt("12u34")
 | 
|  |    290 | 
 | 
| 318 |    291 | import scala.util._
 | 
| 317 |    292 | 
 | 
|  |    293 | def get_me_an_int(s: String) : Option[Int] = 
 | 
|  |    294 |  Try(Some(Integer.parseInt(s))).getOrElse(None)
 | 
|  |    295 | 
 | 
|  |    296 | val lst = List("12345", "foo", "5432", "bar", "x21", "456")
 | 
|  |    297 | for (x <- lst) yield get_me_an_int(x)
 | 
|  |    298 | 
 | 
|  |    299 | // summing up all the numbers
 | 
|  |    300 | 
 | 
|  |    301 | lst.map(get_me_an_int).flatten.sum
 | 
|  |    302 | lst.map(get_me_an_int).flatten.sum
 | 
|  |    303 | 
 | 
|  |    304 | lst.flatMap(get_me_an_int).sum
 | 
|  |    305 | 
 | 
| 318 |    306 | // maps on Options
 | 
|  |    307 | 
 | 
|  |    308 | get_me_an_int("1234").map(even)
 | 
|  |    309 | get_me_an_int("12u34").map(even)
 | 
| 317 |    310 | 
 | 
| 204 |    311 | 
 | 
|  |    312 | 
 | 
| 212 |    313 | // Map type (upper-case)
 | 
|  |    314 | //=======================
 | 
| 204 |    315 | 
 | 
|  |    316 | // Note the difference between map and Map
 | 
|  |    317 | 
 | 
|  |    318 | def factors(n: Int) : List[Int] =
 | 
| 318 |    319 |   (2 until n).toList.filter(n % _ == 0)
 | 
| 204 |    320 | 
 | 
|  |    321 | var ls = (1 to 10).toList
 | 
|  |    322 | val facs = ls.map(n => (n, factors(n)))
 | 
|  |    323 | 
 | 
|  |    324 | facs.find(_._1 == 4)
 | 
|  |    325 | 
 | 
|  |    326 | // works for lists of pairs
 | 
|  |    327 | facs.toMap
 | 
|  |    328 | 
 | 
|  |    329 | 
 | 
|  |    330 | facs.toMap.get(4)
 | 
| 212 |    331 | facs.toMap.getOrElse(42, Nil)
 | 
| 204 |    332 | 
 | 
|  |    333 | val facsMap = facs.toMap
 | 
|  |    334 | 
 | 
|  |    335 | val facsMap0 = facsMap + (0 -> List(1,2,3,4,5))
 | 
| 318 |    336 | facsMap0.get(0)
 | 
| 204 |    337 | 
 | 
| 318 |    338 | val facsMap2 = facsMap + (1 -> List(1,2,3,4,5))
 | 
| 204 |    339 | facsMap.get(1)
 | 
| 318 |    340 | facsMap2.get(1)
 | 
|  |    341 | 
 | 
| 319 |    342 | // groupBy function on Maps
 | 
| 204 |    343 | 
 | 
|  |    344 | val ls = List("one", "two", "three", "four", "five")
 | 
|  |    345 | ls.groupBy(_.length)
 | 
|  |    346 | 
 | 
| 318 |    347 | ls.groupBy(_.length).get(3)
 | 
| 204 |    348 | 
 | 
|  |    349 | 
 | 
| 51 |    350 | 
 | 
| 192 |    351 | 
 | 
|  |    352 | // Pattern Matching
 | 
|  |    353 | //==================
 | 
|  |    354 | 
 | 
|  |    355 | // A powerful tool which is supposed to come to Java in a few years
 | 
|  |    356 | // time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
 | 
|  |    357 | // has it for many years ;o)
 | 
|  |    358 | 
 | 
|  |    359 | // The general schema:
 | 
|  |    360 | //
 | 
|  |    361 | //    expression match {
 | 
|  |    362 | //       case pattern1 => expression1
 | 
|  |    363 | //       case pattern2 => expression2
 | 
|  |    364 | //       ...
 | 
|  |    365 | //       case patternN => expressionN
 | 
|  |    366 | //    }
 | 
|  |    367 | 
 | 
|  |    368 | 
 | 
| 319 |    369 | // recall
 | 
| 192 |    370 | val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
 | 
|  |    371 | 
 | 
| 212 |    372 | def my_flatten(xs: List[Option[Int]]): List[Int] = xs match {
 | 
|  |    373 |   case Nil => Nil 
 | 
|  |    374 |   case None::rest => my_flatten(rest)
 | 
| 318 |    375 |   case Some(v)::rest => v :: my_flatten(rest)
 | 
| 192 |    376 | }
 | 
| 58 |    377 | 
 | 
| 319 |    378 | my_flatten(List(None, Some(1), Some(2), None, Some(3)))
 | 
|  |    379 | 
 | 
| 58 |    380 | 
 | 
| 318 |    381 | // another example with a default case
 | 
| 192 |    382 | def get_me_a_string(n: Int): String = n match {
 | 
| 212 |    383 |   case 0 | 1 | 2 => "small"
 | 
|  |    384 |   case _ => "big"
 | 
| 192 |    385 | }
 | 
|  |    386 | 
 | 
|  |    387 | get_me_a_string(0)
 | 
|  |    388 | 
 | 
| 212 |    389 | 
 | 
| 192 |    390 | // you can also have cases combined
 | 
| 266 |    391 | def season(month: String) : String = month match {
 | 
| 192 |    392 |   case "March" | "April" | "May" => "It's spring"
 | 
|  |    393 |   case "June" | "July" | "August" => "It's summer"
 | 
|  |    394 |   case "September" | "October" | "November" => "It's autumn"
 | 
| 204 |    395 |   case "December" => "It's winter"
 | 
|  |    396 |   case "January" | "February" => "It's unfortunately winter"
 | 
| 192 |    397 | }
 | 
|  |    398 |  
 | 
|  |    399 | println(season("November"))
 | 
|  |    400 | 
 | 
|  |    401 | // What happens if no case matches?
 | 
| 212 |    402 | println(season("foobar"))
 | 
| 192 |    403 | 
 | 
|  |    404 | 
 | 
| 318 |    405 | // days of some months
 | 
| 266 |    406 | def days(month: String) : Int = month match {
 | 
|  |    407 |   case "March" | "April" | "May" => 31
 | 
|  |    408 |   case "June" | "July" | "August" => 30
 | 
|  |    409 | }
 | 
|  |    410 | 
 | 
|  |    411 | 
 | 
| 204 |    412 | // Silly: fizz buzz
 | 
| 192 |    413 | def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
 | 
|  |    414 |   case (0, 0) => "fizz buzz"
 | 
|  |    415 |   case (0, _) => "fizz"
 | 
|  |    416 |   case (_, 0) => "buzz"
 | 
|  |    417 |   case _ => n.toString  
 | 
|  |    418 | }
 | 
|  |    419 | 
 | 
|  |    420 | for (n <- 0 to 20) 
 | 
|  |    421 |  println(fizz_buzz(n))
 | 
|  |    422 | 
 | 
|  |    423 | 
 | 
| 278 |    424 | 
 | 
|  |    425 | 
 | 
| 309 |    426 | // Recursion
 | 
|  |    427 | //===========
 | 
|  |    428 | 
 | 
| 318 |    429 | // well-known example
 | 
|  |    430 | 
 | 
|  |    431 | def fib(n: Int) : Int = { 
 | 
|  |    432 |   if (n == 0 || n == 1) 1
 | 
|  |    433 |    else fib(n - 1) + fib(n - 2)
 | 
|  |    434 | }
 | 
|  |    435 | 
 | 
| 309 |    436 | 
 | 
| 318 |    437 | /* Say you have characters a, b, c.
 | 
|  |    438 |    What are all the combinations of a certain length?
 | 
| 309 |    439 | 
 | 
| 318 |    440 |    All combinations of length 2:
 | 
|  |    441 |   
 | 
|  |    442 |      aa, ab, ac, ba, bb, bc, ca, cb, cc
 | 
|  |    443 | 
 | 
|  |    444 |    Combinations of length 3:
 | 
|  |    445 |    
 | 
|  |    446 |      aaa, baa, caa, and so on......
 | 
| 309 |    447 | */
 | 
|  |    448 | 
 | 
| 318 |    449 | def combs(cs: List[Char], l: Int) : List[String] = {
 | 
| 309 |    450 |   if (l == 0) List("")
 | 
| 318 |    451 |   else for (c <- cs; s <- combs(cs, l - 1)) yield s"$c$s"
 | 
| 309 |    452 | }
 | 
|  |    453 | 
 | 
| 318 |    454 | combs("abc".toList, 2)
 | 
|  |    455 | 
 | 
|  |    456 | 
 | 
|  |    457 | // another well-known example
 | 
| 309 |    458 | 
 | 
|  |    459 | def move(from: Char, to: Char) =
 | 
|  |    460 |   println(s"Move disc from $from to $to!")
 | 
|  |    461 | 
 | 
|  |    462 | def hanoi(n: Int, from: Char, via: Char, to: Char) : Unit = {
 | 
|  |    463 |   if (n == 0) ()
 | 
|  |    464 |   else {
 | 
|  |    465 |     hanoi(n - 1, from, to, via)
 | 
|  |    466 |     move(from, to)
 | 
|  |    467 |     hanoi(n - 1, via, from, to)
 | 
|  |    468 |   }
 | 
|  |    469 | } 
 | 
|  |    470 | 
 | 
| 318 |    471 | hanoi(4, 'A', 'B', 'C')
 | 
| 147 |    472 | 
 | 
|  |    473 | 
 | 
| 318 |    474 | // A Recursive Web Crawler / Email Harvester
 | 
|  |    475 | //===========================================
 | 
| 204 |    476 | //
 | 
| 212 |    477 | // the idea is to look for links using the
 | 
|  |    478 | // regular expression "https?://[^"]*" and for
 | 
|  |    479 | // email addresses using another regex.
 | 
| 204 |    480 | 
 | 
|  |    481 | import io.Source
 | 
|  |    482 | import scala.util._
 | 
|  |    483 | 
 | 
|  |    484 | // gets the first 10K of a web-page
 | 
|  |    485 | def get_page(url: String) : String = {
 | 
|  |    486 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | 
|  |    487 |     getOrElse { println(s"  Problem with: $url"); ""}
 | 
| 147 |    488 | }
 | 
|  |    489 | 
 | 
| 204 |    490 | // regex for URLs and emails
 | 
|  |    491 | val http_pattern = """"https?://[^"]*"""".r
 | 
|  |    492 | val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
 | 
|  |    493 | 
 | 
| 268 |    494 | //test case:
 | 
| 212 |    495 | //email_pattern.findAllIn
 | 
|  |    496 | //  ("foo bla christian@kcl.ac.uk 1234567").toList
 | 
|  |    497 | 
 | 
| 204 |    498 | 
 | 
|  |    499 | // drops the first and last character from a string
 | 
|  |    500 | def unquote(s: String) = s.drop(1).dropRight(1)
 | 
|  |    501 | 
 | 
|  |    502 | def get_all_URLs(page: String): Set[String] = 
 | 
|  |    503 |   http_pattern.findAllIn(page).map(unquote).toSet
 | 
|  |    504 | 
 | 
|  |    505 | // naive version of crawl - searches until a given depth,
 | 
|  |    506 | // visits pages potentially more than once
 | 
| 318 |    507 | def crawl(url: String, n: Int) : Unit = {
 | 
|  |    508 |   if (n == 0) ()
 | 
| 204 |    509 |   else {
 | 
|  |    510 |     println(s"  Visiting: $n $url")
 | 
| 318 |    511 |     for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
 | 
| 204 |    512 |   }
 | 
| 147 |    513 | }
 | 
|  |    514 | 
 | 
| 204 |    515 | // some starting URLs for the crawler
 | 
|  |    516 | val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
 | 
| 147 |    517 | 
 | 
| 204 |    518 | crawl(startURL, 2)
 | 
|  |    519 | 
 | 
|  |    520 | 
 | 
| 318 |    521 | // a primitive email harvester
 | 
|  |    522 | def emails(url: String, n: Int) : Set[String] = {
 | 
|  |    523 |   if (n == 0) Set()
 | 
|  |    524 |   else {
 | 
|  |    525 |     println(s"  Visiting: $n $url")
 | 
|  |    526 |     val page = get_page(url)
 | 
|  |    527 |     val new_emails = email_pattern.findAllIn(page).toSet
 | 
|  |    528 |     new_emails ++ (for (u <- get_all_URLs(page)) yield emails(u, n - 1)).flatten
 | 
|  |    529 |   }
 | 
|  |    530 | }
 | 
| 55 |    531 | 
 | 
| 318 |    532 | emails(startURL, 3)
 | 
| 55 |    533 | 
 | 
|  |    534 | 
 | 
| 318 |    535 | // if we want to explore the internet "deeper", then we
 | 
|  |    536 | // first have to parallelise the request of webpages:
 | 
|  |    537 | //
 | 
|  |    538 | // scala -cp scala-parallel-collections_2.13-0.2.0.jar 
 | 
|  |    539 | // import scala.collection.parallel.CollectionConverters._
 | 
| 55 |    540 | 
 | 
| 53 |    541 | 
 | 
|  |    542 | 
 | 
|  |    543 | 
 | 
| 192 |    544 | 
 | 
| 319 |    545 | // Jumping Towers
 | 
|  |    546 | //================
 | 
| 278 |    547 | 
 | 
| 319 |    548 | 
 | 
|  |    549 | def moves(xs: List[Int], n: Int) : List[List[Int]] = (xs, n) match {
 | 
|  |    550 |   case (Nil, _) => Nil
 | 
|  |    551 |   case (xs, 0) => Nil
 | 
|  |    552 |   case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
 | 
|  |    553 | }
 | 
|  |    554 | 
 | 
|  |    555 | 
 | 
|  |    556 | moves(List(5,1,0), 1)
 | 
|  |    557 | moves(List(5,1,0), 2)
 | 
|  |    558 | moves(List(5,1,0), 5)
 | 
|  |    559 | 
 | 
|  |    560 | // checks whether a jump tour exists at all
 | 
|  |    561 | 
 | 
|  |    562 | def search(xs: List[Int]) : Boolean = xs match {
 | 
|  |    563 |   case Nil => true
 | 
|  |    564 |   case (x::xs) =>
 | 
|  |    565 |     if (xs.length < x) true else moves(xs, x).exists(search(_))
 | 
|  |    566 | }
 | 
|  |    567 | 
 | 
|  |    568 | 
 | 
|  |    569 | search(List(5,3,2,5,1,1))
 | 
|  |    570 | search(List(3,5,1,0,0,0,1))
 | 
|  |    571 | search(List(3,5,1,0,0,0,0,1))
 | 
|  |    572 | search(List(3,5,1,0,0,0,1,1))
 | 
|  |    573 | search(List(3,5,1))
 | 
|  |    574 | search(List(5,1,1))
 | 
|  |    575 | search(Nil)
 | 
|  |    576 | search(List(1))
 | 
|  |    577 | search(List(5,1,1))
 | 
|  |    578 | search(List(3,5,1,0,0,0,0,0,0,0,0,1))
 | 
|  |    579 | 
 | 
|  |    580 | // generate *all* jump tours
 | 
|  |    581 | //    if we are only interested in the shortes one, we could
 | 
|  |    582 | //    shortcircut the calculation and only return List(x) in
 | 
|  |    583 | //    case where xs.length < x, because no tour can be shorter
 | 
|  |    584 | //    than 1
 | 
|  |    585 | // 
 | 
|  |    586 | 
 | 
|  |    587 | def jumps(xs: List[Int]) : List[List[Int]] = xs match {
 | 
|  |    588 |   case Nil => Nil
 | 
|  |    589 |   case (x::xs) => {
 | 
|  |    590 |     val children = moves(xs, x)
 | 
|  |    591 |     val results = children.map(cs => jumps(cs).map(x :: _)).flatten
 | 
|  |    592 |     if (xs.length < x) List(x) :: results else results
 | 
|  |    593 |   }
 | 
|  |    594 | }
 | 
|  |    595 | 
 | 
|  |    596 | jumps(List(3,5,1,2,1,2,1))
 | 
|  |    597 | jumps(List(3,5,1,2,3,4,1))
 | 
|  |    598 | jumps(List(3,5,1,0,0,0,1))
 | 
|  |    599 | jumps(List(3,5,1))
 | 
|  |    600 | jumps(List(5,1,1))
 | 
|  |    601 | jumps(Nil)
 | 
|  |    602 | jumps(List(1))
 | 
|  |    603 | jumps(List(5,1,2))
 | 
|  |    604 | moves(List(1,2), 5)
 | 
|  |    605 | jumps(List(1,5,1,2))
 | 
|  |    606 | jumps(List(3,5,1,0,0,0,0,0,0,0,0,1))
 | 
|  |    607 | 
 | 
|  |    608 | jumps(List(5,3,2,5,1,1)).minBy(_.length)
 | 
|  |    609 | jumps(List(1,3,5,8,9,2,6,7,6,8,9)).minBy(_.length)
 | 
|  |    610 | jumps(List(1,3,6,1,0,9)).minBy(_.length)
 | 
|  |    611 | jumps(List(2,3,1,1,2,4,2,0,1,1)).minBy(_.length)
 | 
|  |    612 | 
 | 
|  |    613 | 
 | 
|  |    614 | 
 |