【问题标题】:Recursive Tcl procedure does not return anything递归 Tcl 过程不返回任何内容
【发布时间】:2016-02-15 19:55:09
【问题描述】:

下面的代码应该为给定的数字返回阶乘 Tcl 脚本使用递归过程作为输入参数。

if {$argc !=1} {
        puts stderr "Error! ns called with wrong number of arguments! ($argc)"
        exit 1
} else {
        set f [lindex $argv 0]
}


proc Fact {x} {
        if { $x==1 } {
                return 1
        }
        return  $x * Fact ($x-1)
}
set res [Fact $f]
puts "Factorial of $f is $res"

但是,它没有给出如下所示的输出:
$ tclsh fact.tcl 5 Factorial of 5 is

我也尝试过return [expr $x * Fact ($x-1)],但它会导致解析错误。我不知道我是否想念 Tcl 中的递归调用。

【问题讨论】:

  • 试试return [expr {$x * [Fact [expr {$x-1}]}]。我稍后会解释为什么...
  • @JohannesKuhn, return [expr {$x * [Fact [expr {$x-1}]]}] 工作,但这种语法有点奇怪,有这么多括号。
  • Tcl 不是从 algol 语法派生的语言。它看起来不像其他语言。

标签: recursion tcl


【解决方案1】:

如果您使用 tcl::mathfunc 命名空间,事情会变得更加整洁:那么您的过程可以在 expr 中使用

% proc ::tcl::mathfunc::fact {n} {
    expr {$n == 1 ? 1 : $n*fact($n-1)}
}
% fact 3
invalid command name "fact"
% expr {fact(3)}
6
% expr {fact(6)}
720

【讨论】:

  • 这个怎么样:proc func {name args body} {proc ::tcl::mathfunc::$name $args [list expr $body]}; func fact n {$n==1 ? 1 : $n*fact($n-1)}...
猜你喜欢
  • 2021-07-23
  • 2011-04-26
  • 2013-09-01
  • 2012-08-23
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多