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