Lists search by first element of a tuple
Ulf Wiger
ulf@REDACTED
Tue Feb 7 21:37:27 CET 2006
Den 2006-02-07 19:53:30 skrev Erlang Questions <erlang@REDACTED>:
> Hi to everyone,
>
> I want to search in a list like:
>
> 1> L=[{{1,2},3},{{1,4},3},{{2,4},8}].
> [{{1,2},3},{{1,4},3},{{2,4},8}]
>
> by the first element of the tuple that is the first element of each
> tuple.
>
> Example, I can use:
>
> 2> lists:filter(fun(X) -> element(1,element(1,X)) == 1 end, L).
> [{{1,2},3},{{1,4},3}]
I think that's about as good as it gets, except perhaps for:
[X || {{1,_},_}=X <- L]
(... assuming the list objects are always two-tuples.
Otherwise:
[X || X <- L, element(1,element(1,X))==1],
but that's not much more elegant than your suggestion.)
> There's a better way to perform such search?
>
> something like:
>
> 3> lists:keysearch({1,_}, 1, L).
> ** 1: variable '_' is unbound **
No, as you noticed. That is not valid Erlang.
Also, lists:keysearch has different semantics
from lists:filter/2. Lists:filter/2 will return
_all_ matches, while lists:keysearch/3 will only
return the first match.
/Uffe
--
Ulf Wiger
More information about the erlang-questions
mailing list