TCL阶乘计算代码:大括号后的额外字符

TCL factorial calculation code: extra characters after close-brace

这是 TCL 中的代码,用于生成用户作为参数给出的数字的阶乘。

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



proc Factorial {x}{
for {set result 1} {$x>1}{set x [expr $x - 1]}{
    set result [expr $result * $x]
}
return $result
}
set res [Factorial $f]
puts "Factorial of $f is $res"

有一个类似的SO question,但它似乎没有直接解决我的问题。我已经仔细检查了语法错误的代码,但它没有通过 tclsh 在 Cygwin 中成功编译,产生了错误:

$ tclsh ext1-1.tcl
extra characters after close-brace
    while executing
"if {$argc !=1}{
        puts stderr "Error! ns called with wrong number of arguments! ($argc)"
        exit 1
} else
        set f [lindex $argv 0]



proc Factorial {x}{..."
    (file "ext1-1.tcl" line 3)

TCL 代码来自:NS Simulator for Beginners,Sophia-Antipolis,2003-2004

Tcl 比大多数语言对空格更敏感(虽然不如 Python)。例如,除了作为命令分隔符的命令之间,您不能添加未转义的换行符。另一组规则是 1) 每个命令都必须以与正确列表相同的方式编写(其中元素由空格分隔)和 2) 命令调用必须具有命令定义指定的参数数量。

由于调用必须看起来像一个正确的列表,代码如下

... {$x>1}{incr x -1} ...

不起作用:以左大括号开头的列表元素必须以匹配的右大括号结束,并且紧跟在与初始左大括号匹配的右大括号之后不能有任何文本。 (这听起来比实际上更复杂。)

参数个数要求意味着

for {set result 1} {$x>1}{incr x -1}{
    set result [expr $result * $x]
}

不会工作,因为 for 命令需要四个参数(开始测试下一个主体)并且它只有两个,start 和其余三个的混搭(实际上什至不是,因为混搭是非法的)。

要使这项工作有效,参数需要分开:

for {set result 1} {$x>1} {incr x -1} {
    set result [expr {$result * $x}]
}

放入空格(或制表符,如果需要)使参数合法且数字正确。