Created
September 6, 2024 08:38
-
-
Save MitchiLaser/76ba41bb37e254852f19223982ba603b to your computer and use it in GitHub Desktop.
TCL upvar abuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/tclsh | |
# TCL has its unique `upvar` method to map a variable from | |
# a superiour scope to a local variable. | |
# This makes it possible to access the values of previous | |
# iterations in recursive functions | |
proc fib {stop {step 0}} { | |
if {$step < 2} { | |
set result [expr $step == 0 ? 0 : 1] ;# first two values | |
} elseif {$step <= $stop} { | |
upvar 1 result previous ;# make result of previous iteration available | |
upvar 2 result preprevious ;# and one further iteration before | |
set result [expr {$previous + $preprevious}] | |
} elseif {$step > $stop} { | |
upvar 1 result result ;# End of recursion | |
return $result | |
} | |
return [fib $stop [expr "$step + 1"]] | |
} | |
puts [fib 20] ;# print 20Th Fibonacci number |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment