diff -r 86a456f8cb92 -r 135bf034ac30 progs/lecture2.scala --- a/progs/lecture2.scala Sat Sep 23 23:49:44 2023 +0100 +++ b/progs/lecture2.scala Wed Nov 01 15:01:32 2023 +0000 @@ -1,54 +1,11 @@ // Scala Lecture 2 //================= - -// String Interpolations -//======================= - -def cube(n: Int) : Int = n * n * n - -val n = 3 -println("The cube of " + n + " is " + cube(n) + ".") - -println(s"The cube of $n is ${cube(n)}.") - -// or even - -println(s"The cube of $n is ${n * n * n}.") - -// helpful for debugging purposes -// -// "The most effective debugging tool is still careful -// thought, coupled with judiciously placed print -// statements." -// — Brian W. Kernighan, in Unix for Beginners (1979) - - -def gcd_db(a: Int, b: Int) : Int = { - println(s"Function called with $a and $b.") - if (b == 0) a else gcd_db(b, a % b) -} - -gcd_db(48, 18) - - - -// you can also implement your own string interpolations - -import scala.language.implicitConversions -import scala.language.reflectiveCalls - -implicit def sring_inters(sc: StringContext) = new { - def i(args: Any*): String = s"\t${sc.s(args:_*)}\n" - def l(args: Any*): String = s"${sc.s(args:_*)}:\n" -} - -// this allows you to write things like - -i"add ${3+2}" -l"some_fresh_name" - - +// - Options +// - Higher-Order Functions (short-hand notation) +// - maps (behind for-comprehensions) +// - Pattern-Matching +// - Recursion // The Option Type //================= @@ -79,6 +36,7 @@ safe_div(10 + 5, 4 - 1) List(1,2,3,4,5,6).indexOf(7) +List[Int]().min List[Int]().minOption def my_min(ls: List[Int]) : Option[Int] = @@ -92,8 +50,8 @@ // Try(something).getOrElse(what_to_do_in_case_of_an_exception) // -import scala.util._ -import io.Source +import scala.util._ // Try,... +import io.Source // fromURL val my_url = "https://nms.kcl.ac.uk/christian.urban/" @@ -399,9 +357,10 @@ // Pattern Matching //================== -// A powerful tool which is supposed to come to Java in -// a few years time (https://www.youtube.com/watch?v=oGll155-vuQ). -// ...Scala already has it for many years ;o) +// A powerful tool which has even landed in Java during +// the last few years (https://inside.java/2021/06/13/podcast-017/). +// ...Scala already has it for many years and the concept is +// older than your friendly lecturer, that is stone old ;o) // The general schema: // @@ -420,8 +379,8 @@ case x::xs => f(x)::my_map_int(xs, f) } -def my_map_option(o: Option[Int], f: Int => Int) : Option[Int] = - o match { +def my_map_option(opt: Option[Int], f: Int => Int) : Option[Int] = + opt match { case None => None case Some(x) => Some(f(x)) }