progs/lecture1.scala
changeset 26 a7afc2540a88
parent 25 6253f4681451
child 32 45557ad18ea6
--- a/progs/lecture1.scala	Wed Nov 09 15:07:23 2016 +0000
+++ b/progs/lecture1.scala	Thu Nov 10 00:15:14 2016 +0000
@@ -1,7 +1,7 @@
 // Lecture 1
 //===========
 
-// Assignments (values)
+// Value assignments
 // (variable names should be lower case)
 //======================================
 
@@ -32,7 +32,7 @@
 println("test")
 
 
-val tst = "This is a " + "test" 
+val tst = "This is a " ++ "test\n" 
 println(tst)
 
 val lst = List(1,2,3,1)
@@ -132,7 +132,6 @@
    ==     equals
    !      not
    && ||  and, or
-   
 */
 
 
@@ -141,23 +140,43 @@
 
 fact2(150)
 
+
 def fib(n: Int): Int =
   if (n == 0) 1 else
-    if (n == 1) 1 else fib(n - 1) + f(n - 2)
+    if (n == 1) 1 else fib(n - 1) + fib(n - 2)
 
 
-//a recursive function
-def gcd(x: Int, y: Int): Int = 2 //??? 
+//gcd - Euclid's algorithm
+
+def gcd(a: Int, b: Int): Int =
+  if (b == 0) a else gcd(b, a % b)
+
+gcd(48, 18)
+
 
 // String Interpolations
 //=======================
 
+val n = 3
+println("The square of " + n + " is " + square(n) + ".")
+
+println(s"The square of ${n} is ${square(n)}.")
+
+
+
+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)
+
 
 // Assert/Testing
 //================
 
-// For-Maps (not For-Loops)
-//==========================
+// For-Comprehensions (not For-Loops)
+//====================================
 
 for (n <- (1 to 10).toList) yield square(n)
 
@@ -165,10 +184,19 @@
      m <- (1 to 10).toList) yield m * n
 
 
-val mtable = for (n <- (1 to 10).toList; 
-                  m <- (1 to 10).toList) yield m * n
+val mult_table = 
+  for (n <- (1 to 10).toList; 
+       m <- (1 to 10).toList) yield m * n
+
+mult_table.sliding(10,10).mkString("\n")
+
 
-mtable.sliding(10,10).mkString("\n")
+// with patterns
+
+for ((m, n) <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield m + n 
+
+for (p <- List((1, 4), (2, 3), (3, 2), (4, 1))) yield p._1 + p._2 
+
 
 
 // Webpages