progs/lecture3.scala
changeset 494 253d1ccb65de
parent 493 244df77507c2
--- a/progs/lecture3.scala	Sun Sep 15 12:57:59 2024 +0100
+++ b/progs/lecture3.scala	Mon Jul 21 16:38:07 2025 +0100
@@ -10,6 +10,36 @@
 // - string interpolations
 // - Pattern-Matching
 
+def fact(n: BigInt) : BigInt = {
+  if (n == 0) 1 
+  else n * fact(n - 1)
+}
+
+def fib(n: BigInt) : BigInt = {
+  if (n == 0) 1
+  else if (n == 1) 1 
+  else fib(n - 1) + fib(n - 2)
+}
+
+
+
+
+
+def inc(n: Int) : Int = n + 1
+
+for (n <- List(1,2,3,4)) yield inc(n)
+
+List().map(inc)
+
+
+
+my_map(inc, List(1,2,3,4))
+
+
+
+
+
+
 // A Recursive Web Crawler / Email Harvester
 //===========================================
 //
@@ -79,6 +109,12 @@
 // EFFICIENT AND FAST, just explaining exhaustive
 // depth-first search
 
+//> using dep org.scala-lang.modules::scala-parallel-collections:1.0.4
+import scala.collection.parallel.CollectionConverters.*
+
+
+val s1 = "s\n"
+val s2 = """s\n"""
 
 val game0 = """.14.6.3..
               |62...4..9
@@ -286,6 +322,14 @@
 //       case patternN => expressionN
 //    }
 
+def my_map(f: Int => Int, xs: List[Int]) : List[Int] =  
+  xs match {
+    case Nil => Nil 
+    case hd::tl => f(hd) ::  my_map(f, tl)
+  }
+
+my_map(x => x * x, List(1,2,3,4))
+
 
 // recall
 def len(xs: List[Int]) : Int = {
@@ -350,6 +394,8 @@
 // more interesting patterns for lists - calculate the deltas between 
 // elements
 
+List(4,3,2,1) -> List(1,1,.. )
+
 def delta(xs: List[Int]) : List[Int] = xs match {
   case Nil => Nil
   case x::Nil => x::Nil
@@ -386,6 +432,13 @@
 val lf = Leaf(20)
 val tr = Node("foo", Leaf(10), Leaf(23))
 
+def sizet(t: Tree) : Int = t match {
+  case Leaf(_) => 1
+  case Node(_, left , right) => 1 + sizet(left) + sizet(right)
+}
+
+sizet(tr)
+
 val lst : List[Tree] = List(lf, tr)