Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: proplists:get_value/2 or pattern matching?

Tags:

erlang

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 image 800
user601836 Avatar asked Apr 17 '13 07:04

user601836


People also ask

How does pattern matching work in Erlang?

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.

How does pattern matching work in Linux?

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.

What is assignment in Erlang programming language?

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.

Which side of the list should match the pattern?

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.


1 Answers

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.

like image 187
Hynek -Pichi- Vychodil Avatar answered Oct 12 '22 23:10

Hynek -Pichi- Vychodil