progs/lecture2.scala
changeset 365 fc118ee0fce4
parent 364 f1a6fa599d26
child 366 1c829680503e
--- a/progs/lecture2.scala	Sun Nov 22 03:45:22 2020 +0000
+++ b/progs/lecture2.scala	Mon Nov 23 02:43:03 2020 +0000
@@ -392,9 +392,9 @@
 // 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 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)
 
 // The general schema:
 //
@@ -407,24 +407,20 @@
 
 
 // recall
-val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
-
-def my_flatten(xs: List[Option[Int]]): List[Int] = 
-xs match {
-  case Nil => Nil 
-  case None::rest => my_flatten(rest)
-  case Some(v)::rest => v :: my_flatten(rest)
-}
+def my_map_int(lst: List[Int], f: Int => Int) : List[Int] = 
+  lst match {
+    case Nil => Nil
+    case x::xs => f(x)::my_map_int(xs, f)
+  }
 
-my_flatten(List(None, Some(1), Some(2), None, Some(3)))
-
+def my_map_option(o: Option[Int], f: Int => Int) : Option[Int] = 
+  o match {
+    case None => None
+    case Some(x) => Some(f(x))
+  }
 
-// another example with a default case
-def get_me_a_string(n: Int): String = n match {
-  case 0 | 1 | 2 => "small"
-}
-
-get_me_a_string(3)
+my_map_option(None, x => x * x)
+my_map_option(Some(8), x => x * x)
 
 
 // you can also have cases combined
@@ -434,20 +430,17 @@
   case "September" | "October" | "November" => "It's autumn"
   case "December" => "It's winter"
   case "January" | "February" => "It's unfortunately winter"
-}
- 
-println(season("November"))
-
-// What happens if no case matches?
-println(season("foobar"))
-
-
-// days of some months
-def days(month: String) : Int = month match {
-  case "March" | "April" | "May" => 31
-  case "June" | "July" | "August" => 30
+  case _ => "Wrong month"
 }
 
+// pattern-match on integers
+
+def fib(n: Int) : Int = n match { 
+  case 0 | 1 => 1
+  case n => fib(n - 1) + fib(n - 2)
+}
+
+fib(10)
 
 // Silly: fizz buzz
 def fizz_buzz(n: Int) : String = (n % 3, n % 5) match {
@@ -457,22 +450,31 @@
   case _ => n.toString  
 }
 
-for (n <- 0 to 20) 
+for (n <- 1 to 20) 
  println(fizz_buzz(n))
 
 
+val lst = List(None, Some(1), Some(2), None, Some(3)).flatten
+
+def my_flatten(xs: List[Option[Int]]): List[Int] = 
+ xs match {
+   case Nil => Nil 
+   case None::rest => my_flatten(rest)
+   case Some(v)::rest => v :: my_flatten(rest)
+ }
+
+my_flatten(List(None, Some(1), Some(2), None, Some(3)))
+
+
+
+ 
+
+
 
 
 // Recursion
 //===========
 
-// well-known example
-
-def fib(n: Int) : Int = { 
-  if (n == 0 || n == 1) 1
-   else fib(n - 1) + fib(n - 2)
-}
-
 
 /* Say you have characters a, b, c.
    What are all the combinations of a certain length?