[erlang-questions] List comprehension question

Fred Hebert <>
Thu Jan 16 18:59:20 CET 2014


Learn You Some Erlang mentions that feature! In the list comprehensions
section of the first chapter (http://learnyousomeerlang.com/starting-out-for-real#list-comprehensions)
the following example is used:

    Note that the generator expressions coupled with pattern matching also
    act as a filter:

        6> Weather = [{toronto, rain}, {montreal, storms}, {london, fog},
        6>            {paris, sun}, {boston, fog}, {vancouver, snow}].
        [{toronto,rain},
         {montreal,storms},
         {london,fog},
         {paris,sun},
         {boston,fog},
         {vancouver,snow}]
        7> FoggyPlaces = [X || {X, fog} <- Weather].
        [london,boston]

    If an element of the list 'Weather' doesn't match the {X, fog} pattern,
    it's simply ignored in the list comprehension whereas the = operator
    would have thrown an exception.

Binary comprehensions are introduced in the same chapter.

Regards,
Fred.

On 01/16, 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
> 
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list