summaryrefslogtreecommitdiff
path: root/gcd.tcl
diff options
context:
space:
mode:
authorIgor Pashev <pashev.igor@gmail.com>2011-04-10 22:29:52 +0400
committerIgor Pashev <pashev.igor@gmail.com>2011-04-10 22:29:52 +0400
commit8d0f362d8098a7c7d93fe1087739a74754bebf4c (patch)
tree98410f27ef7b93ac3b6d3cea8017d30eb0e21e63 /gcd.tcl
parentfa27781d02045206442d76f380a23568d3a13336 (diff)
downloadgcd-8d0f362d8098a7c7d93fe1087739a74754bebf4c.tar.gz
TCL
Diffstat (limited to 'gcd.tcl')
-rwxr-xr-xgcd.tcl36
1 files changed, 36 insertions, 0 deletions
diff --git a/gcd.tcl b/gcd.tcl
new file mode 100755
index 0000000..8aa30fe
--- /dev/null
+++ b/gcd.tcl
@@ -0,0 +1,36 @@
+#!/usr/bin/env tclsh
+#
+# TESTED WITH TCL 8.5
+# There is no tail recursion optimization before tcl 8.6.
+# See also: http://wiki.tcl.tk/1348
+#
+# SYNOPSIS:
+# tclsh8.5 gcd.tcl 11 22 33 44 121
+#
+# chmod +x gcd.tcl
+# ./gcd.tcl 11 22 33 44 121
+#
+
+# http://wiki.tcl.tk/14726
+proc foldl {func init list} {
+ foreach item $list { set init [invoke $func $init $item] }
+ return $init
+}
+proc invoke {func args} { uplevel #0 $func $args }
+
+
+# } and else must be in the same line
+proc gcd2 {a b} {
+ if {$b == 0} {
+ return $a
+ } else {
+ return [gcd2 $b [ expr {$a % $b} ]]
+ }
+}
+
+proc gcdn {numbers} {
+ return [foldl gcd2 0 $numbers]
+}
+
+puts [gcdn $argv]
+