Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Difference between lmap and foreach?

711 views
Skip to first unread message

Bhushit Joshipura

unread,
Oct 2, 2016, 1:53:41 PM10/2/16
to
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"
}
a 1
b 2
c 3
d 4
{} {} {} {}
% foreach i $list1 j $list2 {
puts "$i $j"
}
a 1
b 2
c 3
d 4
%

Rich

unread,
Oct 2, 2016, 2:21:30 PM10/2/16
to
For your example above, lmap is a "collecting foreach". The final four
empty items you see are the return result list from lmap, obtained by
collecting each return result from executing "puts" on each item in the
two lists. Since "puts" returns an empty string, you get four empty
strings within a list.

foreach does not collect and return the results from executing its body
so you don't get an extra {} {} {} {} from foreach.

Christian Gollwitzer

unread,
Oct 2, 2016, 5:04:54 PM10/2/16
to
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
0 new messages