Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically update list

Status
Not open for further replies.

sh00der

Technical User
Jul 15, 2003
58
CA
Is there a way to update a list from within a foreach loop that is working on the list? Here's an example ...

set nos [list 1 2 3 4 5 6]

% foreach one $nos {
if {$one == 4} {
lappend nos 7
}
if {$one == 7} {puts "List dynamically updated"}
}

This code does update the list but doesn't produce the output. Any offers?
 
I think (on very little evidence at all!) that what happens is this:
When the for loop is evaluated the elements of the list are identified by the interpreter. Thereafter, whatever you do to the list won't change the scope of the loop.

Obviously you have something more complex in mind than your example. There must be a way to make it work and the static-ness of the loop scope may (probably) actually be useful. What are you really trying to do? Maybe the forum can help.

Bob Rashkin
rrashkin@csc.com
 
It's an interesting issue and calls for recursion at
the least. Bong is right and practical. What do you
want?
Here is a fun little example.
Code:
proc reeval {list cond {times "0"}} {
 if {$times > 3} {return} 
                     foreach p $list {
                             if {$p == $cond} {
                                lappend list [expr $p + 1]
                                puts "List = $list" 
                                set cond [expr int(1 + rand() * [llength $list])]
                                set times [expr $times + 1]
                                return [reeval $list $cond $times]   
                              }
                    }
return $list
}
Usage:
set list {127 489 48 9 59 45}
set list [reeval $list 9]
 
Bong, my actual application is a fairly complex GUI but I'm basically just doing data manipulation. I could just search through the modified list a second time but when there is a large amount of items this could add significant time to the procedure.

I can probably come up with a complicated method to achieve what I want but I just wanted to make sure that I wasn't missing a simple alternative. Thanks for the post.
 
I've cracked it! In case anyone's interested, here's how I did it,

set nos [list 1 2 3 4 5 6]
for {set c 0} {$c <= [llength $nos]} {incr c} {
set one [lindex $nos $c]
if {$one == 4} {lappend nos 7}
if {$one == 7} {puts "Works"}
}

I think this must make the substitution for [llength $nos] at each increment of c, allowing dynamic modification.

Thanks anyway.
 
sh00der, yes of course. pretty obvious.
however, I would rather use recursion...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top