Hi Luc,
Lookup the documentation for "proc" and you'll see that "args" when used
as the last argument is special.
-mike
On 11/26/2022 9:05 PM, Luc wrote:
I want to parse a list of numbers and find the one that is
the closest to a target number:
proc closest {target args} {
set closest 9999999999999999999
puts $args
foreach i $args {
puts "i is $i"
if {$i > $target} {set diff [expr $i - $target]}
if {$target > $i} {set diff [expr $target - $i]}
if {$diff < $closest} {set closest $diff; set ret $i} >> }
return $ret
}
Testing on Tkcon:
% closest 456 [list 45 256 987 599 362]
args is {45 256 987 599 362}
i is 45 256 987 599 362
missing operator at _@_
in expression "456 - 45 _@_256 987 599 362"
Well, so $args is a list. But $i is not treated as an item
of the list in the foreach loop. Why not?
Let's try again:
proc closest {target args} {
set closest 9999999999999999999
puts $args
foreach i {*}$args {
puts "i is $i"
if {$i > $target} {set diff [expr $i - $target]}
if {$target > $i} {set diff [expr $target - $i]}
if {$diff < $closest} {set closest $diff; set ret $i} >> }
return $ret
}
% closest 456 [list 45 256 987 599 362]
args is {45 256 987 599 362}
i is 45
i is 256
i is 987
i is 599
i is 362
362
It works with the nipple! Why?
I want to parse a list of numbers and find the one that is
the closest to a target number:
proc closest {target args} {
set closest 9999999999999999999
puts $args
foreach i $args {
puts "i is $i"
if {$i > $target} {set diff [expr $i - $target]}
if {$target > $i} {set diff [expr $target - $i]}
if {$diff < $closest} {set closest $diff; set ret $i}
}
return $ret
}
Testing on Tkcon:
% closest 456 [list 45 256 987 599 362]
args is {45 256 987 599 362}
i is 45 256 987 599 362
missing operator at _@_
in expression "456 - 45 _@_256 987 599 362"
Well, so $args is a list. But $i is not treated as an item
of the list in the foreach loop. Why not?
Let's try again:
proc closest {target args} {
set closest 9999999999999999999
puts $args
foreach i {*}$args {
puts "i is $i"
if {$i > $target} {set diff [expr $i - $target]}
if {$target > $i} {set diff [expr $target - $i]}
if {$diff < $closest} {set closest $diff; set ret $i}
}
return $ret
}
% closest 456 [list 45 256 987 599 362]
args is {45 256 987 599 362}
i is 45
i is 256
i is 987
i is 599
i is 362
362
It works with the nipple! Why?
| Sysop: | Keyop |
|---|---|
| Location: | Huddersfield, West Yorkshire, UK |
| Users: | 714 |
| Nodes: | 16 (2 / 14) |
| Uptime: | 133:45:38 |
| Calls: | 12,087 |
| Files: | 14,997 |
| Messages: | 6,517,349 |