progs/lecture3.scala
changeset 375 ddda2e76a40f
parent 374 90b267768329
child 418 fa7f7144f2bb
equal deleted inserted replaced
374:90b267768329 375:ddda2e76a40f
   211 foo(List(2,2,2,3))
   211 foo(List(2,2,2,3))
   212 
   212 
   213 // Tail recursion
   213 // Tail recursion
   214 //================
   214 //================
   215 
   215 
   216 
   216 def fact(n: BigInt): BigInt = 
   217 def fact(n: Long): Long = 
       
   218   if (n == 0) 1 else n * fact(n - 1)
   217   if (n == 0) 1 else n * fact(n - 1)
   219 
       
   220 def factB(n: BigInt): BigInt = 
       
   221   if (n == 0) 1 else n * factB(n - 1)
       
   222 
       
   223 factB(100000)
       
   224 
   218 
   225 fact(10)              //ok
   219 fact(10)              //ok
   226 fact(10000)           // produces a stackoverflow
   220 fact(10000)           // produces a stackoverflow
       
   221 
   227 
   222 
   228 def factT(n: BigInt, acc: BigInt): BigInt =
   223 def factT(n: BigInt, acc: BigInt): BigInt =
   229   if (n == 0) acc else factT(n - 1, n * acc)
   224   if (n == 0) acc else factT(n - 1, n * acc)
   230 
   225 
   231 factT(10, 1)
   226 factT(10, 1)
   244 // generates loop-like code, which does not need
   239 // generates loop-like code, which does not need
   245 // to allocate stack-space in each recursive
   240 // to allocate stack-space in each recursive
   246 // call; Scala can do this only for tail-recursive
   241 // call; Scala can do this only for tail-recursive
   247 // functions
   242 // functions
   248 
   243 
   249 
   244 def length(xs: List[Int]) : Int = xs match {
       
   245   case Nil => 0
       
   246   case _ :: tail => 1 + length(tail)
       
   247 }
       
   248 
       
   249 @tailrec
       
   250 def lengthT(xs: List[Int], acc : Int) : Int = xs match {
       
   251   case Nil => acc
       
   252   case _ :: tail => lengthT(tail, 1 + acc)
       
   253 }
       
   254 
       
   255 lengthT(List.fill(10000000)(1), 0)
   250 
   256 
   251 
   257 
   252 // Sudoku
   258 // Sudoku
   253 //========
   259 //========
   254 
   260 
   292   if (isDone(game)) List(game)
   298   if (isDone(game)) List(game)
   293   else 
   299   else 
   294     candidates(game, emptyPosition(game)).par.
   300     candidates(game, emptyPosition(game)).par.
   295       map(c => search(update(game, empty(game), c))).toList.flatten
   301       map(c => search(update(game, empty(game), c))).toList.flatten
   296 }
   302 }
       
   303 
   297 
   304 
   298 def search1T(games: List[String]): Option[String] = games match {
   305 def search1T(games: List[String]): Option[String] = games match {
   299   case Nil => None
   306   case Nil => None
   300   case game::rest => {
   307   case game::rest => {
   301     if (isDone(game)) Some(game)
   308     if (isDone(game)) Some(game)