Вопрос

How can I read a tuple key and value in Erlang?

I have this variable:

Params = [<<"TPUIBrowser">>,0,18,
 {[{<<"End">>,<<"location-1ÿ">>},{<<"Start">>,<<"location-1">>}]},
 null]

and I would like to get the values for <<"End">> and <<"Start">>.

How could I do that in Erlang?

I can do it like this:

[_,_,_,A,_] = Params.
{[{_,B},{_,C}]} = A.

But this feels very verbose and error prone (i.e. when I get sent more params). What would be the best erlang way?

Это было полезно?

Решение

There are functions for this in the lists library. Check out lists:keyfind:

[_,_,_,{A},_] = Params,
{Key, Value} = lists:keyfind(<<"End">>, 1, A).

(I assume you know where in Params you have A)

Другие советы

Alternatively you can use records which are particularly suitable if you plan to add more fields.

Since you use a list here {[{_,B},{_,C}]} = A. I assume that there might be more elements; in this case, making a recursive function to unpack it could be better.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top