an unexpected (to me) difference between lists:map/2 and list comprehension

Ulf Wiger ulf@REDACTED
Tue Aug 8 13:16:52 CEST 2006


Den 2006-08-08 08:03:34 skrev Bengt Kleberg <bengt.kleberg@REDACTED>:

> greetings,
>
> there is a difference between lists:map/2 and list comprehension that  
> can hide errors in the code. the generator part works like a filter,  
> silently dropping unmatched items in the list. it would be nice if this  
> was mentioned in the documentation.
>
>
> from the documentation and examples of list comprehension  
> (http://www.erlang.se/doc/doc-5.5/doc/programming_examples/part_frame.html)  
> i have assumed that the generator part works like the fun head in  
> lists:map/2 (or lists:filter/2, etc).
> ie the following two pices of code would be equivalent:
>
> 1) [A || {A, B, C} <- L].
> 2) lists:map( fun({A, B, C}) -> A end, L).

You ought to replace 1) with something like this:

1) [begin {A,B,C} = X, A end || X <- L]

or

1) [(fun({A,B,C}) -> A end)(X) || X <- L]

Just remember that the <- construct is a filter,
and the LHS is where some operation is applied
to the selection.

BR,
Ulf W
-- 
Ulf Wiger



More information about the erlang-questions mailing list