Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding a value in {key, value} list in Erlang

I'm new to Erlang and maybe I just missed this issue in the tutorial though it is trivial. Let's say, I have a list of {Key, Value} pairs gotten from erlang:fun_info/1. I want to know function arity, the rest of the list is no interest to me. So I write something like:

find_value( _, [] ) ->
    nothing;
find_value( Key, [{Key, Value} | _] ) ->
    Value;
find_value( Key, [_ | T] ) ->
    find_value( Key, T).    

And then do:

find_value( arity, erlang:fun_info( F )).

I works fine, but should something like find_value be a too common routine to write it? I failed to find its' analogue in BIFs though. So the question is: it there a nice elegant way to get a value for a key from a list of {key, value} tuples?

like image 415
akalenuk Avatar asked Jun 03 '12 11:06

akalenuk


People also ask

How do I find the length of a list in Erlang?

You can use length() to find the length of a list, and can use list comprehensions to filter your list. num(L) -> length([X || X <- L, X < 1]).

How do I add a list in Erlang?

The List is a structure used to store a collection of data items. In Erlang, Lists are created by enclosing the values in square brackets.


2 Answers

The module proplists contains get_value/2, which should be what you want.

like image 98
aronisstav Avatar answered Oct 14 '22 00:10

aronisstav


lists:keyfind/3 does this. Here I've mapped it into your find_value/2 interface:

find_value(Key, List) ->
    case lists:keyfind(Key, 1, List) of
        {Key, Result} -> Result;
        false -> nothing
    end.

proplists may be an even better route, though.

like image 32
Emil Vikström Avatar answered Oct 14 '22 02:10

Emil Vikström