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