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.
Like many other functional languages, Erlang has powerful pattern matching capabilities. Typically, a pattern (left side) is matched against a term (right side). Pattern matching can also occur in receive blocks, in which case the pattern is matched against the existing messages in a process queue.
Pattern matching can also occur in receive blocks, in which case the pattern is matched against the existing messages in a process queue. If the pattern match operation succeeds, then any unbound variables in the pattern will be bound.
There is nothing like an assignment in Erlang programming language; there is a different approach to accessing values in memory, which is the pattern-matching operations.
Note that in the fourth example, the pipe (|) signifying the head and tail of the list as described in Terms. Also note that the left hand side should match the right hand side which is the normal case for patterns.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With