[erlang-questions] Request feedback on example project

Siraaj Khandkar <>
Thu Feb 4 21:09:33 CET 2016


On 2/3/16 7:20 PM, Kostis Sagonas wrote:
>>....
> While at it, I suggest to use a list comprehension instead of lists:map.
>

Why?


I use comprehensions occasionally, but never as first pick, for 2 reasons:


(1) surprising filter semantics:

1> L = [{foo, a}, {bar, b}].
[{foo,a},{bar,b}]
2>
2>  [X || {foo, X} <-L].
[a]
3>

While lists:map/2 crashes, as expected:

3> lists:map(fun ({foo, X}) -> X end, L).
** exception error: no function clause matching 
erl_eval:'-inside-an-interpreted-fun-'({bar,b})
4>

There're certainly ways around that, such as:

4>  [begin {foo, Foo} = X, Foo end || X <- L].
** exception error: no match of right hand side value {bar,b}
5>
5>  [(fun ({foo, Foo}) -> Foo end)(X) || X <- L].
** exception error: no function clause matching 
erl_eval:'-inside-an-interpreted-fun-'({bar,b})
6>

But all that feels like extra gymnastics to just use list comprehensions 
for the sake of using list comprehensions.


(2) Explicitly-declared intention. When you explicitly call "filter" and 
"map" - I have an immediate high-level idea of where you're going with 
it, but list comprehensions tempt one to conflate things, so it is 
harder to understand the intention (there're some gnarly ones out in the 
wild...).


Surely, YMMV, but this is just my, correct, opinion WRT to blanket "just 
use list comprehensions" recommendations ;-)


More information about the erlang-questions mailing list