--- a/progs/lecture3.scala Fri Nov 27 15:03:50 2020 +0000
+++ b/progs/lecture3.scala Sat Nov 28 12:09:55 2020 +0000
@@ -213,18 +213,13 @@
// Tail recursion
//================
-
-def fact(n: Long): Long =
+def fact(n: BigInt): BigInt =
if (n == 0) 1 else n * fact(n - 1)
-def factB(n: BigInt): BigInt =
- if (n == 0) 1 else n * factB(n - 1)
-
-factB(100000)
-
fact(10) //ok
fact(10000) // produces a stackoverflow
+
def factT(n: BigInt, acc: BigInt): BigInt =
if (n == 0) acc else factT(n - 1, n * acc)
@@ -246,7 +241,18 @@
// call; Scala can do this only for tail-recursive
// functions
+def length(xs: List[Int]) : Int = xs match {
+ case Nil => 0
+ case _ :: tail => 1 + length(tail)
+}
+@tailrec
+def lengthT(xs: List[Int], acc : Int) : Int = xs match {
+ case Nil => acc
+ case _ :: tail => lengthT(tail, 1 + acc)
+}
+
+lengthT(List.fill(10000000)(1), 0)
// Sudoku
@@ -295,6 +301,7 @@
map(c => search(update(game, empty(game), c))).toList.flatten
}
+
def search1T(games: List[String]): Option[String] = games match {
case Nil => None
case game::rest => {