Search code examples
listtclin-place

is there a destructive version of lmap


I want to run lmap, but do it destructively, i.e., on the list itself. I can use, of course,
set listy [ lmap x $listy { func1 x } ]
But is there something else?
Thanks.


Solution

  • There's no built-in command for that. You need to do a bit of looping:

    set items {q w e r t y u i o p}
    
    # iterate over the indices
    for {set idx 0} {$idx < [llength $items]} {incr idx} {
        # get the item
        set item [lindex $items $idx]
    
        # generate an updated item
        set item [string toupper $item]
    
        # put the updated item back
        lset items $idx $item
    }
    
    puts $items
    

    Note that values are conceptually copy-on-write (though the under-the-covers implementation is more efficient than that); anything that had the list before you run your loop won't see the updates unless they reread the variable containing it. This is better in practice (lower bug rate) than values changing under one's feet...