tcl 查找列表的最大元素 [英] tcl find the max element of a list
问题描述
我是 tcl 的新手,我正在尝试获取给定列表中的最大元素我写了一个打印最大值的函数,但它不能正常工作这是代码
i am new to tcl , i am trying to get the max element in a given list i wrote a function that prints the max but it is not working properly here is the code
proc findmax { items } {
set max 1
foreach i $items {
if { $i > $max } {
set $max $i
}
}
puts "max is = $max"
}
我这样调用函数:
findmax $items
这是我通过的列表:
set items { 12 2 5 4 2 6 7 55 8 9 6 4}
但它输出 1 而不是预期的 55
but it outputs 1 and not 55 as expected
推荐答案
你的问题是这一行:
set $max $i
在 Tcl 中,$
字符意味着从命名变量中读取并将该值用作(可能是)命令参数的一部分.这意味着总是.没有例外(当然,除非反斜杠或{
大括号}
).因此,在循环的第一次迭代中(替换后):
In Tcl, the $
character means read from the named variable and use that value as (possibly part of) the argument to a command. It means this always. No exceptions (unless backslash-quoted or in {
braces}
, of course). Thus, on the first iteration of the loop you're getting (after substitution):
set 1 12
变量名 1
是合法的,但不寻常,不是你想要的.为了让算法起作用,您需要为 set
命令指定要设置的变量的 name,max
,结果如下:
The variable name 1
is legal, but unusual and not what you want. For the algorithm to work, you instead want to give the set
command the name of the variable to set, max
, resulting in this:
set max $i
这将在第一次迭代时替换为:
which will be substituted to this on the first iteration:
set max 12
看起来不错!未来编程的一个很好的经验法则是,如果一个命令操作一个变量(设置它或更新它),那么你需要传递变量的名称,而不是从中检索到的值.
That looks right! A good rule of thumb for future programming is that if a command manipulates a variable (setting it or updating it) then you need to pass the name of the variable, not the value retrieved from it.
获取列表最大值的标准方法是单行:
The standard method of getting the maximum value of a list is a one-liner:
set max [tcl::mathfunc::max {*}$items]
这使用内置函数 max
(在 ::tcl::mathfunc
命名空间中)并在 items 中传递列表的内容
作为多个参数,都作为一个步骤.{*}$
序列是变量读取语法规则与列表扩展规则的组合,您可能还没有真正考虑过.但是,编写自己的最大值查找器作为学习练习仍然是一个很好的练习.
This uses the built-in function max
(which is in the ::tcl::mathfunc
namespace) and passes the contents of the list in items
as multiple arguments, all as one step. The {*}$
sequence is a combination of the variable-read syntax rule with the list-expansion rule, which you've probably not really thought about yet. However it's still a good exercise to write your own maximum finder as a learning exercise.
这篇关于tcl 查找列表的最大元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!