Am 02.10.16 um 19:53 schrieb Bhushit Joshipura:
> This must be FAQ.
> I am dusting off my Tcl and am working on writing some control structure.
> In my previous stint with Tcl, I totally missed lmap and also had not known a particular use of foreach.
> Now I read both and find them confusing - at least foreach seems to have a superset of functionality of lmap - except for the last empty elements lmap prints in my case...
>
> Do I understand lmap correctly?
> TIA,
> -Bhushit
>
> % set list1 {a b c d}
> a b c d
> % set list2 {1 2 3 4}
> 1 2 3 4
> % lmap i $list1 j $list2 {
> puts "$i $j"
> }
lmap is meant to be used in a different way. "map" is a term widely used
in functional languages to apply a function to each element of a list.
So does lmap. Try:
set list2 {1 2 3 4}
set result [lmap x $list2 {expr {2*$x}}]
If doing this with foreach, you would need to fiddle with lappend and
create the empty list first. So, actually, lmap is a superset of what
foreach does, it collects the results of the loop body (otherwise
discarded in foreach) into a new list and returns that.
Actually an even more general concept is "List comprehension", built
natively into many modern scripting languages. An implementation for Tcl
can be found here:
http://wiki.tcl.tk/12574
Christian