progs/lecture3.scala
changeset 448 db2a3e3287a9
parent 418 fa7f7144f2bb
child 449 d67c5f7177a6
--- a/progs/lecture3.scala	Mon Nov 21 15:57:45 2022 +0000
+++ b/progs/lecture3.scala	Fri Nov 25 00:03:15 2022 +0000
@@ -1,6 +1,57 @@
 // Scala Lecture 3
 //=================
 
+// - maps (behind for-comprehensions)
+// - Pattern-Matching
+
+abstract class Rexp
+case object ZERO extends Rexp                      // matches nothing
+case object ONE extends Rexp                       // matches the empty string
+case class CHAR(c: Char) extends Rexp              // matches a character c
+case class ALT(r1: Rexp, r2: Rexp) extends Rexp    // alternative
+case class SEQ(r1: Rexp, r2: Rexp) extends Rexp    // sequence
+case class STAR(r: Rexp) extends Rexp              // star
+
+def depth(r: Rexp) : Int = r match {
+  case ZERO => 1
+  case ONE => 1
+  case CHAR(_) => 1
+  case ALT(r1, r2) => 1 + List(depth(r1), depth(r2)).max
+  case SEQ(r1, r2) => 1 + List(depth(r1), depth(r2)).max
+  case STAR(r1) => 1 + depth(r1)
+}
+
+
+// - String-Interpolations
+
+// 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)
 
 
 // naive quicksort with "On" function