| 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)
 | 
| 320 |    131 | Integer.parseInt("12u34")
 | 
| 318 |    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 | 
 | 
| 320 |    156 | Try({
 | 
|  |    157 |   val x = 3
 | 
|  |    158 |   val y = 0
 | 
|  |    159 |   Some(x / y)
 | 
|  |    160 | }).getOrElse(None)
 | 
| 204 |    161 | 
 | 
| 323 |    162 | 
 | 
|  |    163 | // minOption 
 | 
|  |    164 | // maxOption 
 | 
|  |    165 | // minByOption 
 | 
|  |    166 | // maxByOption
 | 
|  |    167 | 
 | 
| 204 |    168 | // Higher-Order Functions
 | 
|  |    169 | //========================
 | 
|  |    170 | 
 | 
|  |    171 | // functions can take functions as arguments
 | 
| 319 |    172 | // and produce functions as result
 | 
| 204 |    173 | 
 | 
|  |    174 | def even(x: Int) : Boolean = x % 2 == 0
 | 
|  |    175 | def odd(x: Int) : Boolean = x % 2 == 1
 | 
|  |    176 | 
 | 
|  |    177 | val lst = (1 to 10).toList
 | 
| 320 |    178 | lst.reverse.sorted
 | 
|  |    179 | 
 | 
| 204 |    180 | 
 | 
|  |    181 | lst.filter(even)
 | 
| 320 |    182 | lst.count(odd)
 | 
| 212 |    183 | lst.find(even)
 | 
| 320 |    184 | lst.exists(even)
 | 
| 212 |    185 | 
 | 
| 320 |    186 | lst.filter(_ < 4) 
 | 
|  |    187 | lst.filter(x => x % 2 == 1)
 | 
| 318 |    188 | lst.filter(_ % 2 == 0)
 | 
| 204 |    189 | 
 | 
| 320 |    190 | 
 | 
|  |    191 | lst.sortWith((x, y) => x > y)
 | 
| 212 |    192 | lst.sortWith(_ < _)
 | 
| 204 |    193 | 
 | 
| 318 |    194 | // but this only works when the arguments are clear, but 
 | 
|  |    195 | // not with multiple occurences
 | 
|  |    196 | lst.find(n => odd(n) && n > 2)
 | 
|  |    197 | 
 | 
|  |    198 | 
 | 
|  |    199 | val ps = List((3, 0), (3, 2), (4, 2), (2, 2), (2, 0), (1, 1), (1, 0))
 | 
|  |    200 | 
 | 
| 212 |    201 | def lex(x: (Int, Int), y: (Int, Int)) : Boolean = 
 | 
|  |    202 |   if (x._1 == y._1) x._2 < y._2 else x._1 < y._1
 | 
|  |    203 | 
 | 
|  |    204 | ps.sortWith(lex)
 | 
| 204 |    205 | 
 | 
| 320 |    206 | ps.sortBy(x => x._1)
 | 
| 204 |    207 | ps.sortBy(_._2)
 | 
|  |    208 | 
 | 
|  |    209 | ps.maxBy(_._1)
 | 
|  |    210 | ps.maxBy(_._2)
 | 
|  |    211 | 
 | 
|  |    212 | 
 | 
| 212 |    213 | // maps (lower-case)
 | 
|  |    214 | //===================
 | 
| 204 |    215 | 
 | 
| 212 |    216 | def double(x: Int): Int = x + x
 | 
| 204 |    217 | def square(x: Int): Int = x * x
 | 
|  |    218 | 
 | 
| 212 |    219 | 
 | 
| 204 |    220 | val lst = (1 to 10).toList
 | 
|  |    221 | 
 | 
| 212 |    222 | lst.map(x => (double(x), square(x)))
 | 
|  |    223 | 
 | 
| 204 |    224 | lst.map(square)
 | 
|  |    225 | 
 | 
| 319 |    226 | // this is actually how for-comprehensions are
 | 
|  |    227 | // defined in Scala
 | 
| 204 |    228 | 
 | 
|  |    229 | lst.map(n => square(n))
 | 
|  |    230 | for (n <- lst) yield square(n)
 | 
|  |    231 | 
 | 
|  |    232 | // this can be iterated
 | 
|  |    233 | 
 | 
|  |    234 | lst.map(square).filter(_ > 4)
 | 
|  |    235 | 
 | 
| 320 |    236 | (lst.map(square)
 | 
|  |    237 |    .filter(_ > 4)
 | 
|  |    238 |    .map(square))
 | 
| 204 |    239 | 
 | 
|  |    240 | 
 | 
| 318 |    241 | // lets define our own higher-order functions
 | 
|  |    242 | // type of functions is for example Int => Int
 | 
| 204 |    243 | 
 | 
| 212 |    244 | 
 | 
| 320 |    245 | 0 :: List(3,4,5,6)
 | 
|  |    246 | 
 | 
|  |    247 | 
 | 
| 204 |    248 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = {
 | 
|  |    249 |   if (lst == Nil) Nil
 | 
|  |    250 |   else f(lst.head) :: my_map_int(lst.tail, f)
 | 
|  |    251 | }
 | 
|  |    252 | 
 | 
|  |    253 | my_map_int(lst, square)
 | 
|  |    254 | 
 | 
|  |    255 | 
 | 
|  |    256 | // same function using pattern matching: a kind
 | 
|  |    257 | // of switch statement on steroids (see more later on)
 | 
|  |    258 | 
 | 
| 319 |    259 | def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = 
 | 
|  |    260 | lst match {
 | 
| 204 |    261 |   case Nil => Nil
 | 
|  |    262 |   case x::xs => f(x)::my_map_int(xs, f)
 | 
|  |    263 | }
 | 
|  |    264 | 
 | 
|  |    265 | 
 | 
|  |    266 | // other function types
 | 
|  |    267 | //
 | 
|  |    268 | // f1: (Int, Int) => Int
 | 
|  |    269 | // f2: List[String] => Option[Int]
 | 
|  |    270 | // ... 
 | 
| 212 |    271 | val lst = (1 to 10).toList
 | 
| 204 |    272 | 
 | 
| 320 |    273 | lst.sum
 | 
|  |    274 | 
 | 
|  |    275 | val lst = List(1,2,3,4)
 | 
|  |    276 | 
 | 
|  |    277 | lst.head
 | 
|  |    278 | lst.tail
 | 
|  |    279 | 
 | 
|  |    280 | def sumOf(f: Int => Int, lst: List[Int]): Int = 
 | 
|  |    281 | lst match {
 | 
| 204 |    282 |   case Nil => 0
 | 
| 320 |    283 |   case x::foo => f(x) + sumOf(f, foo)
 | 
| 204 |    284 | }
 | 
|  |    285 | 
 | 
|  |    286 | def sum_squares(lst: List[Int]) = sumOf(square, lst)
 | 
|  |    287 | def sum_cubes(lst: List[Int])   = sumOf(x => x * x * x, lst)
 | 
|  |    288 | 
 | 
|  |    289 | sum_squares(lst)
 | 
|  |    290 | sum_cubes(lst)
 | 
|  |    291 | 
 | 
| 318 |    292 | // lets try a factorial
 | 
| 212 |    293 | def fact(n: Int) : Int = 
 | 
|  |    294 |   if (n == 0) 1 else n * fact(n - 1)
 | 
| 204 |    295 | 
 | 
|  |    296 | def sum_fact(lst: List[Int]) = sumOf(fact, lst)
 | 
|  |    297 | sum_fact(lst)
 | 
|  |    298 | 
 | 
|  |    299 | 
 | 
|  |    300 | 
 | 
| 318 |    301 | // sometimes it is needed that you specify the type. 
 | 
| 317 |    302 | (1 to 100).filter((x: Int) => x % 2 == 0).sum 
 | 
|  |    303 | 
 | 
| 319 |    304 | // in this case it is clear that x must be an Int
 | 
| 317 |    305 | (1 to 100).filter(x => x % 2 == 0).sum
 | 
|  |    306 | 
 | 
| 319 |    307 | // When each parameter (only x in this case) is used only once
 | 
| 317 |    308 | // you can use the wizardy placeholder syntax
 | 
|  |    309 | (1 to 100).filter(_ % 2 == 0).sum
 | 
|  |    310 | 
 | 
|  |    311 | 
 | 
|  |    312 | 
 | 
| 318 |    313 | // Option Type and maps
 | 
|  |    314 | //======================
 | 
| 317 |    315 | 
 | 
|  |    316 | // a function that turns strings into numbers (similar to .toInt)
 | 
|  |    317 | Integer.parseInt("12u34")
 | 
|  |    318 | 
 | 
| 318 |    319 | import scala.util._
 | 
| 317 |    320 | 
 | 
|  |    321 | def get_me_an_int(s: String) : Option[Int] = 
 | 
|  |    322 |  Try(Some(Integer.parseInt(s))).getOrElse(None)
 | 
|  |    323 | 
 | 
|  |    324 | val lst = List("12345", "foo", "5432", "bar", "x21", "456")
 | 
|  |    325 | for (x <- lst) yield get_me_an_int(x)
 | 
|  |    326 | 
 | 
|  |    327 | // summing up all the numbers
 | 
|  |    328 | 
 | 
|  |    329 | lst.map(get_me_an_int).flatten.sum
 | 
|  |    330 | lst.map(get_me_an_int).flatten.sum
 | 
|  |    331 | 
 | 
|  |    332 | lst.flatMap(get_me_an_int).sum
 | 
|  |    333 | 
 | 
| 318 |    334 | // maps on Options
 | 
|  |    335 | 
 | 
| 320 |    336 | get_me_an_int("12345").map(even)
 | 
| 318 |    337 | get_me_an_int("12u34").map(even)
 | 
| 317 |    338 | 
 | 
| 320 |    339 | def my_map_option(o: Option[Int], f : Int => Int) : Option[Int] = {
 | 
|  |    340 | o match {
 | 
|  |    341 |    case None => None
 | 
|  |    342 |    case Some(foo) => Some(f(foo))
 | 
|  |    343 | }}
 | 
|  |    344 | 
 | 
|  |    345 | my_map_option(Some(4), square)
 | 
|  |    346 | my_map_option(None, square)
 | 
|  |    347 | 
 | 
| 204 |    348 | 
 | 
|  |    349 | 
 | 
| 212 |    350 | // Map type (upper-case)
 | 
|  |    351 | //=======================
 | 
| 204 |    352 | 
 | 
|  |    353 | // Note the difference between map and Map
 | 
|  |    354 | 
 | 
| 320 |    355 | val ascii = ('a' to 'z').map(c => (c, c.toInt)).toList
 | 
|  |    356 | 
 | 
|  |    357 | val ascii_Map = ascii.toMap
 | 
|  |    358 | 
 | 
|  |    359 | 
 | 
| 204 |    360 | def factors(n: Int) : List[Int] =
 | 
| 318 |    361 |   (2 until n).toList.filter(n % _ == 0)
 | 
| 204 |    362 | 
 | 
|  |    363 | var ls = (1 to 10).toList
 | 
|  |    364 | val facs = ls.map(n => (n, factors(n)))
 | 
|  |    365 | 
 | 
|  |    366 | facs.find(_._1 == 4)
 | 
|  |    367 | 
 | 
|  |    368 | // works for lists of pairs
 | 
|  |    369 | facs.toMap
 | 
|  |    370 | 
 | 
|  |    371 | 
 | 
| 320 |    372 | facs.toMap.get(40)
 | 
| 212 |    373 | facs.toMap.getOrElse(42, Nil)
 | 
| 204 |    374 | 
 | 
|  |    375 | val facsMap = facs.toMap
 | 
|  |    376 | 
 | 
|  |    377 | val facsMap0 = facsMap + (0 -> List(1,2,3,4,5))
 | 
| 318 |    378 | facsMap0.get(0)
 | 
| 204 |    379 | 
 | 
| 318 |    380 | val facsMap2 = facsMap + (1 -> List(1,2,3,4,5))
 | 
| 204 |    381 | facsMap.get(1)
 | 
| 318 |    382 | facsMap2.get(1)
 | 
|  |    383 | 
 | 
| 319 |    384 | // groupBy function on Maps
 | 
| 204 |    385 | 
 | 
|  |    386 | val ls = List("one", "two", "three", "four", "five")
 | 
|  |    387 | ls.groupBy(_.length)
 | 
|  |    388 | 
 | 
| 320 |    389 | ls.groupBy(_.length).get(5)
 | 
| 204 |    390 | 
 | 
|  |    391 | 
 | 
| 51 |    392 | 
 | 
| 192 |    393 | 
 | 
|  |    394 | // Pattern Matching
 | 
|  |    395 | //==================
 | 
|  |    396 | 
 | 
|  |    397 | // A powerful tool which is supposed to come to Java in a few years
 | 
|  |    398 | // time (https://www.youtube.com/watch?v=oGll155-vuQ)...Scala already
 | 
|  |    399 | // has it for many years ;o)
 | 
|  |    400 | 
 | 
|  |    401 | // The general schema:
 | 
|  |    402 | //
 | 
|  |    403 | //    expression match {
 | 
|  |    404 | //       case pattern1 => expression1
 | 
|  |    405 | //       case pattern2 => expression2
 | 
|  |    406 | //       ...
 | 
|  |    407 | //       case patternN => expressionN
 | 
|  |    408 | //    }
 | 
|  |    409 | 
 | 
|  |    410 | 
 | 
| 319 |    411 | // recall
 | 
| 192 |    412 | val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
 | 
|  |    413 | 
 | 
| 320 |    414 | def my_flatten(xs: List[Option[Int]]): List[Int] = 
 | 
|  |    415 | xs match {
 | 
| 212 |    416 |   case Nil => Nil 
 | 
|  |    417 |   case None::rest => my_flatten(rest)
 | 
| 318 |    418 |   case Some(v)::rest => v :: my_flatten(rest)
 | 
| 192 |    419 | }
 | 
| 58 |    420 | 
 | 
| 319 |    421 | my_flatten(List(None, Some(1), Some(2), None, Some(3)))
 | 
|  |    422 | 
 | 
| 58 |    423 | 
 | 
| 318 |    424 | // another example with a default case
 | 
| 192 |    425 | def get_me_a_string(n: Int): String = n match {
 | 
| 212 |    426 |   case 0 | 1 | 2 => "small"
 | 
| 192 |    427 | }
 | 
|  |    428 | 
 | 
| 320 |    429 | get_me_a_string(3)
 | 
| 192 |    430 | 
 | 
| 212 |    431 | 
 | 
| 192 |    432 | // you can also have cases combined
 | 
| 266 |    433 | def season(month: String) : String = month match {
 | 
| 192 |    434 |   case "March" | "April" | "May" => "It's spring"
 | 
|  |    435 |   case "June" | "July" | "August" => "It's summer"
 | 
|  |    436 |   case "September" | "October" | "November" => "It's autumn"
 | 
| 204 |    437 |   case "December" => "It's winter"
 | 
|  |    438 |   case "January" | "February" => "It's unfortunately winter"
 | 
| 192 |    439 | }
 | 
|  |    440 |  
 | 
|  |    441 | println(season("November"))
 | 
|  |    442 | 
 | 
|  |    443 | // What happens if no case matches?
 | 
| 212 |    444 | println(season("foobar"))
 | 
| 192 |    445 | 
 | 
|  |    446 | 
 | 
| 318 |    447 | // days of some months
 | 
| 266 |    448 | def days(month: String) : Int = month match {
 | 
|  |    449 |   case "March" | "April" | "May" => 31
 | 
|  |    450 |   case "June" | "July" | "August" => 30
 | 
|  |    451 | }
 | 
|  |    452 | 
 | 
|  |    453 | 
 | 
| 204 |    454 | // Silly: fizz buzz
 | 
| 192 |    455 | def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
 | 
|  |    456 |   case (0, 0) => "fizz buzz"
 | 
|  |    457 |   case (0, _) => "fizz"
 | 
|  |    458 |   case (_, 0) => "buzz"
 | 
|  |    459 |   case _ => n.toString  
 | 
|  |    460 | }
 | 
|  |    461 | 
 | 
|  |    462 | for (n <- 0 to 20) 
 | 
|  |    463 |  println(fizz_buzz(n))
 | 
|  |    464 | 
 | 
|  |    465 | 
 | 
| 278 |    466 | 
 | 
|  |    467 | 
 | 
| 309 |    468 | // Recursion
 | 
|  |    469 | //===========
 | 
|  |    470 | 
 | 
| 318 |    471 | // well-known example
 | 
|  |    472 | 
 | 
|  |    473 | def fib(n: Int) : Int = { 
 | 
|  |    474 |   if (n == 0 || n == 1) 1
 | 
|  |    475 |    else fib(n - 1) + fib(n - 2)
 | 
|  |    476 | }
 | 
|  |    477 | 
 | 
| 309 |    478 | 
 | 
| 318 |    479 | /* Say you have characters a, b, c.
 | 
|  |    480 |    What are all the combinations of a certain length?
 | 
| 309 |    481 | 
 | 
| 318 |    482 |    All combinations of length 2:
 | 
|  |    483 |   
 | 
|  |    484 |      aa, ab, ac, ba, bb, bc, ca, cb, cc
 | 
|  |    485 | 
 | 
|  |    486 |    Combinations of length 3:
 | 
|  |    487 |    
 | 
|  |    488 |      aaa, baa, caa, and so on......
 | 
| 309 |    489 | */
 | 
|  |    490 | 
 | 
| 320 |    491 | def combs(cs: List[Char], n: Int) : List[String] = {
 | 
|  |    492 |   if (n == 0) List("")
 | 
|  |    493 |   else for (c <- cs; s <- combs(cs, n - 1)) yield s"$c$s"
 | 
|  |    494 | }
 | 
|  |    495 | 
 | 
|  |    496 | combs(List('a', 'b', 'c'), 3)
 | 
|  |    497 | 
 | 
|  |    498 | 
 | 
|  |    499 | 
 | 
| 318 |    500 | def combs(cs: List[Char], l: Int) : List[String] = {
 | 
| 309 |    501 |   if (l == 0) List("")
 | 
| 318 |    502 |   else for (c <- cs; s <- combs(cs, l - 1)) yield s"$c$s"
 | 
| 309 |    503 | }
 | 
|  |    504 | 
 | 
| 318 |    505 | combs("abc".toList, 2)
 | 
|  |    506 | 
 | 
|  |    507 | 
 | 
| 147 |    508 | 
 | 
| 318 |    509 | // A Recursive Web Crawler / Email Harvester
 | 
|  |    510 | //===========================================
 | 
| 204 |    511 | //
 | 
| 212 |    512 | // the idea is to look for links using the
 | 
|  |    513 | // regular expression "https?://[^"]*" and for
 | 
|  |    514 | // email addresses using another regex.
 | 
| 204 |    515 | 
 | 
|  |    516 | import io.Source
 | 
|  |    517 | import scala.util._
 | 
|  |    518 | 
 | 
|  |    519 | // gets the first 10K of a web-page
 | 
|  |    520 | def get_page(url: String) : String = {
 | 
|  |    521 |   Try(Source.fromURL(url)("ISO-8859-1").take(10000).mkString).
 | 
|  |    522 |     getOrElse { println(s"  Problem with: $url"); ""}
 | 
| 147 |    523 | }
 | 
|  |    524 | 
 | 
| 204 |    525 | // regex for URLs and emails
 | 
|  |    526 | val http_pattern = """"https?://[^"]*"""".r
 | 
|  |    527 | val email_pattern = """([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})""".r
 | 
|  |    528 | 
 | 
| 268 |    529 | //test case:
 | 
| 212 |    530 | //email_pattern.findAllIn
 | 
|  |    531 | //  ("foo bla christian@kcl.ac.uk 1234567").toList
 | 
|  |    532 | 
 | 
| 204 |    533 | 
 | 
|  |    534 | // drops the first and last character from a string
 | 
|  |    535 | def unquote(s: String) = s.drop(1).dropRight(1)
 | 
|  |    536 | 
 | 
|  |    537 | def get_all_URLs(page: String): Set[String] = 
 | 
|  |    538 |   http_pattern.findAllIn(page).map(unquote).toSet
 | 
|  |    539 | 
 | 
|  |    540 | // naive version of crawl - searches until a given depth,
 | 
|  |    541 | // visits pages potentially more than once
 | 
| 318 |    542 | def crawl(url: String, n: Int) : Unit = {
 | 
|  |    543 |   if (n == 0) ()
 | 
| 204 |    544 |   else {
 | 
|  |    545 |     println(s"  Visiting: $n $url")
 | 
| 318 |    546 |     for (u <- get_all_URLs(get_page(url))) crawl(u, n - 1)
 | 
| 204 |    547 |   }
 | 
| 147 |    548 | }
 | 
|  |    549 | 
 | 
| 204 |    550 | // some starting URLs for the crawler
 | 
|  |    551 | val startURL = """https://nms.kcl.ac.uk/christian.urban/"""
 | 
| 147 |    552 | 
 | 
| 204 |    553 | crawl(startURL, 2)
 | 
|  |    554 | 
 | 
|  |    555 | 
 | 
| 318 |    556 | // a primitive email harvester
 | 
|  |    557 | def emails(url: String, n: Int) : Set[String] = {
 | 
|  |    558 |   if (n == 0) Set()
 | 
|  |    559 |   else {
 | 
|  |    560 |     println(s"  Visiting: $n $url")
 | 
|  |    561 |     val page = get_page(url)
 | 
|  |    562 |     val new_emails = email_pattern.findAllIn(page).toSet
 | 
|  |    563 |     new_emails ++ (for (u <- get_all_URLs(page)) yield emails(u, n - 1)).flatten
 | 
|  |    564 |   }
 | 
|  |    565 | }
 | 
| 55 |    566 | 
 | 
| 318 |    567 | emails(startURL, 3)
 | 
| 55 |    568 | 
 | 
|  |    569 | 
 | 
| 318 |    570 | // if we want to explore the internet "deeper", then we
 | 
|  |    571 | // first have to parallelise the request of webpages:
 | 
|  |    572 | //
 | 
|  |    573 | // scala -cp scala-parallel-collections_2.13-0.2.0.jar 
 | 
|  |    574 | // import scala.collection.parallel.CollectionConverters._
 | 
| 55 |    575 | 
 | 
| 53 |    576 | 
 | 
|  |    577 | 
 | 
|  |    578 | 
 | 
| 192 |    579 | 
 | 
| 319 |    580 | // Jumping Towers
 | 
|  |    581 | //================
 | 
| 278 |    582 | 
 | 
| 319 |    583 | 
 | 
|  |    584 | def moves(xs: List[Int], n: Int) : List[List[Int]] = (xs, n) match {
 | 
|  |    585 |   case (Nil, _) => Nil
 | 
|  |    586 |   case (xs, 0) => Nil
 | 
|  |    587 |   case (x::xs, n) => (x::xs) :: moves(xs, n - 1)
 | 
|  |    588 | }
 | 
|  |    589 | 
 | 
|  |    590 | 
 | 
|  |    591 | moves(List(5,1,0), 1)
 | 
|  |    592 | moves(List(5,1,0), 2)
 | 
|  |    593 | moves(List(5,1,0), 5)
 | 
|  |    594 | 
 | 
|  |    595 | // checks whether a jump tour exists at all
 | 
|  |    596 | 
 | 
|  |    597 | def search(xs: List[Int]) : Boolean = xs match {
 | 
|  |    598 |   case Nil => true
 | 
|  |    599 |   case (x::xs) =>
 | 
|  |    600 |     if (xs.length < x) true else moves(xs, x).exists(search(_))
 | 
|  |    601 | }
 | 
|  |    602 | 
 | 
|  |    603 | 
 | 
|  |    604 | search(List(5,3,2,5,1,1))
 | 
|  |    605 | search(List(3,5,1,0,0,0,1))
 | 
|  |    606 | search(List(3,5,1,0,0,0,0,1))
 | 
|  |    607 | search(List(3,5,1,0,0,0,1,1))
 | 
|  |    608 | search(List(3,5,1))
 | 
|  |    609 | search(List(5,1,1))
 | 
|  |    610 | search(Nil)
 | 
|  |    611 | search(List(1))
 | 
|  |    612 | search(List(5,1,1))
 | 
|  |    613 | search(List(3,5,1,0,0,0,0,0,0,0,0,1))
 | 
|  |    614 | 
 | 
|  |    615 | // generate *all* jump tours
 | 
|  |    616 | //    if we are only interested in the shortes one, we could
 | 
|  |    617 | //    shortcircut the calculation and only return List(x) in
 | 
|  |    618 | //    case where xs.length < x, because no tour can be shorter
 | 
|  |    619 | //    than 1
 | 
|  |    620 | // 
 | 
|  |    621 | 
 | 
|  |    622 | def jumps(xs: List[Int]) : List[List[Int]] = xs match {
 | 
|  |    623 |   case Nil => Nil
 | 
|  |    624 |   case (x::xs) => {
 | 
|  |    625 |     val children = moves(xs, x)
 | 
|  |    626 |     val results = children.map(cs => jumps(cs).map(x :: _)).flatten
 | 
|  |    627 |     if (xs.length < x) List(x) :: results else results
 | 
|  |    628 |   }
 | 
|  |    629 | }
 | 
|  |    630 | 
 | 
|  |    631 | jumps(List(3,5,1,2,1,2,1))
 | 
|  |    632 | jumps(List(3,5,1,2,3,4,1))
 | 
|  |    633 | jumps(List(3,5,1,0,0,0,1))
 | 
|  |    634 | jumps(List(3,5,1))
 | 
|  |    635 | jumps(List(5,1,1))
 | 
|  |    636 | jumps(Nil)
 | 
|  |    637 | jumps(List(1))
 | 
|  |    638 | jumps(List(5,1,2))
 | 
|  |    639 | moves(List(1,2), 5)
 | 
|  |    640 | jumps(List(1,5,1,2))
 | 
|  |    641 | jumps(List(3,5,1,0,0,0,0,0,0,0,0,1))
 | 
|  |    642 | 
 | 
|  |    643 | jumps(List(5,3,2,5,1,1)).minBy(_.length)
 | 
|  |    644 | jumps(List(1,3,5,8,9,2,6,7,6,8,9)).minBy(_.length)
 | 
|  |    645 | jumps(List(1,3,6,1,0,9)).minBy(_.length)
 | 
|  |    646 | jumps(List(2,3,1,1,2,4,2,0,1,1)).minBy(_.length)
 | 
|  |    647 | 
 | 
|  |    648 | 
 | 
|  |    649 | 
 |