[erlang-questions] Request feedback on example project

Kostis Sagonas kostis@REDACTED
Thu Feb 4 21:18:36 CET 2016


On 02/04/2016 09:09 PM, Siraaj Khandkar wrote:
> 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?

Did you even bother looking at the code I was referring to, or you 
simply wanted to take something off your chest?

The relavant code (which was included in my mail) read:

=========================================================
-spec read_uuid_string(list()) -> uuid() | bad_uuid.
read_uuid_string(UUID) ->
     Parts = string:tokens(UUID, "{-}"),
     case lists:map(fun length/1, Parts) of
          ...
=========================================================

There is no filter here.  The corresponding list comprehension is:

     [length(P) || P <- Parts]

and is shorter and nicer.  That's why.

Kostis

PS. With most of the rest that you write below, I agree.


> 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 ;-)
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list