How to efficiently (mem / time) change all list items in Tcl?

To work with each element of the list, returning the changed list, different languages ​​have explicit constructs.

In Perl mapping:

perl -e 'my @a = (1..4); print join(q( ), map { $_ * $_ } @a)'
1 4 9 16

Python has a list of concepts:

>>> a = (1,2,3,4)
>>> [el*el for el in a]
[1, 4, 9, 16]

What is the most efficient way to do this in Tcl? I can come up with a regular foreach loop.

set l {}
foreach i {1 2 3 4} {
    lappend l [expr $i * $i]
}
puts $l
1 4 9 16

Is this the fastest way?

As for memory efficiency, this creates a second list, one by one. If I don't need a list forever, is there a better way?

And finally, is there anything shorter? I could not find the information here or at http://wiki.tcl.tk

Answer:

Donal Fellows , , proc {}, Tcl . Tcl "" . http://wiki.tcl.tk/12848

+5
2

:

set idx 0
foreach item $theList {
    lset theList $idx [expr {$item * $item}]
    incr idx
}

(, ), , ( ) :

foreach item $theList {
    lappend newList [expr {$item * $item}]
}

, foreach , ( - ), , { }. , , : , time, , .

+8

, - ( tcllib struct:: list), .

package require struct::list
puts [struct::list mapfor x $data { expr {$x * $x} }]
+1

All Articles