[erlang-questions] List comprehension question

Ivan Uemlianin ivan@REDACTED
Thu Jan 16 18:08:21 CET 2014


I interpret the "{X,Y} <- L" as a filter type expression, as well as a 
generator, equivalent to something like "Z <- L, {X,Y} = Z".

Ivan


On 16/01/2014 16:39, Rich Neswold wrote:
> Hello,
>
> This morning I became aware of a (powerful) feature of list
> comprehensions. Take the following example:
>
>      [ X + Y || {X, Y} <- L].
>
> If we set L to [{1,2}, ok, {1,3}], we get the result [3,4] instead of
> a pattern match exception (as I was expecting.) This means that list
> comprehensions give you a "free" lists:filter/2 in the generator
> expressions!
>
> I've looked through the OTP documentation, quite a few Stack Overflow
> questions, and several list comprehension tutorials and none of them
> explicitly state that generator expressions filter elements that don't
> match their pattern. The web pages emphasize generators and guards are
> like combinations of lists:map and lists:filter, which isn't exactly
> correct. For instance, the above example is not the same as:
>
>      lists:map(fun ({X, Y}) -> X + Y end, L).
>
> but is more equivalent to:
>
>      lists:foldr(fun ({X, Y}, Acc) -> [X + Y | Acc];
>                      (_, Acc) -> Acc
>                  end, [], L).
>
> Is this an expected, but undocumented, feature of list comprehensions?
> Or am I in "undefined behavior" territory?
>
> --
> Rich
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>

-- 
============================================================
Ivan A. Uemlianin PhD
Llaisdy
Speech Technology Research and Development

                     ivan@REDACTED
                      www.llaisdy.com
                          llaisdy.wordpress.com
               github.com/llaisdy
                      www.linkedin.com/in/ivanuemlianin

                         festina lente
============================================================



More information about the erlang-questions mailing list