Version 0 of Trampoline

Updated 2005-04-09 10:03:10 by suchenwi

Richard Suchenwirh 2005-04-09 - A trampoline is a software device to repeatedly call some code until a terminal condition is met. It can give the effect of recursion without consuming much stack. Slightly rewritten from Playing TRAC, here is a simple trampoline:

 proc trampoline form {
    while 1 {
      set new [subst $form]
       if {$new eq $form} break
       set form $new
    set form

#-- Testing with the classic factorial - either constant 1 is returned, or a bracketed expression for the next trampoline jump:

 proc fac n {
    expr {$n<=1? 1: "\[expr $n * \[fac [incr n -1]]]"}

See also Tail call optimization | Tail call optimisation (both have their merits :)

Category Concept | Arts and crafts of Tcl-Tk programming