[erlang-questions] list comprehension with match

Schneider <>
Fri Feb 10 17:19:15 CET 2017


Hi list,

I have a list of items that I want to extract data from _and_ check to 
make sure they are all of the same type.
When I use

     Member_keys = [Key || #member{key = Key} <- Members].

all members that are not #member records are dropped silently, but I 
want it to crash ! The match works as a filter.
Using:

     Member_keys = lists:foldl(fun(#member{key = Key}, Keys) ->
                       [Key | Keys]
                   end, [], Members),

or

     getkeys([#member{key = Key} | Tail]) ->
         [Key | getkeys(Tail)];
     getkeys([]) -> [].

does exactly what I am looking for.

According to [1], a list comprehension [Expr(E) || E <- List] is 
basically translated to:

     'lc^0'([E|Tail], Expr) ->
         [Expr(E)|'lc^0'(Tail, Expr)];
     'lc^0'([], _Expr) -> [].

but that doesn't explain this behaviour.

Could somebody explain to me what is going on?


[1] http://erlang.org/doc/efficiency_guide/listHandling.html#id68285


More information about the erlang-questions mailing list