Skip to content

Instantly share code, notes, and snippets.

@MitchiLaser
Created September 6, 2024 08:38
Show Gist options
  • Save MitchiLaser/76ba41bb37e254852f19223982ba603b to your computer and use it in GitHub Desktop.
Save MitchiLaser/76ba41bb37e254852f19223982ba603b to your computer and use it in GitHub Desktop.
TCL upvar abuse
#!/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