Version 4 of Tail call optimisation

Updated 2004-07-08 08:22:03 by mjk

mjk: Here is a simple example of using the after for tail-recursive calls. The following example calculates Fibonacci numbers without exhausting the stack.

 proc _fib {i a b} {
     if {$i <= 2} then {
         set ::_fibretval [expr $a + $b]
     } else {
         after 0 _fib [expr $i - 1] $b [expr $a + $b]
     }
 }

 proc fib {i} {
     after 0 _fib $i 0 1
     vwait ::_fibretval

     return $::_fibretval
 }

 puts [fib  1] ;# => 1
 puts [fib  2] ;# => 1
 puts [fib  3] ;# => 2
 puts [fib 10] ;# => 55
 puts [fib 30] ;# => 832040
 puts [fib 46] ;# => 1836311903

(mjk: remember to add here a short explanation, what the code does.)