5

I have a list of tuples that has always the same form (i.e. the tuples come always in the same order):

1> L = [{a, 1}. {b,2}, {c, 3}, {d, 4}].

Knowing that the list has only a few elements, what is the best way to extract the values associated to the keys?

Suppose the list is passed as argument to a function, to extract the values should I use:

proplists:get_value(a, L).
proplists:get_value(b, L).
...
proplists:get_valus(d, L).

Or should I simply use pattern matching as:

[{a, 1}. {b,2}, {c, 3}, {d, 4}] = L.
4

1 回答 1

7

If you really know your lists is in same form pattern matching is simplest

[{a, A}, {b, B}, {c, C}, {d, D}] = L,

you can compare it with following

[A, B, C, D] = [ proplists:get_value(X, L) || X <- [a,b,c,d] ],

or

A = proplists:get_value(a, L),
B = proplists:get_value(b, L),
C = proplists:get_value(c, L),
D = proplists:get_value(d, L),

or

[A, B, C, D] = [ V || Key <- [a,b,c,d], {K, V} <- L, K =:= Key ],

Pattern matching will be also fastest. You can also use lists:keyfind/3 which is implemented as Bif and is way faster than proplist:get_value/2 but it doesn't matter for short lists.

于 2013-04-17T08:16:57.147 回答