Finding a value in {key, value} list in Erlang
Solution 1
The module proplists
contains get_value/2
, which should be what you want.
Solution 2
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.
Solution 3
Since lists:keyfind/3 was already posted, I'll mention another useful option, using lists comprehensions:
hd([ Value || {arity, Value} <- List ]).
This means getting all the values such that each element is "Value" and comes from a tuple that matches {arity, Value} inside List. Since a list comprehension returns a list, we get the head of that list.
And using it in a fun:
1> List=[{a,1},{b,2},{c,3}].
[{a,1},{b,2},{c,3}]
2> F=fun(What, List) -> hd([ Value || {Key, Value} <- List, Key =:= What]) end.
#Fun<erl_eval.12.82930912>
3> F(c, List).
3
Solution 4
proplists:get_value Is the way to do it if you don't care about the speed
lists:keyfind It is the best choice for performance since is a BIF. You can wrapit with a element/2 like this
element(2, lists:keyfind(K, 1, L))
And you will get the same result of proplists:get_value but faster.
Source: http://www.ostinelli.net/erlang-listskeyfind-or-proplistsget_value/
Solution 5
find(K, [H|T]) ->
case H of
{K, V} -> V;
_ -> find(K, T)
end;
find(_, []) -> none.
Muhammad Asif
NTUU "KPI": M. Sc. Bravo Interactive: C, C++, MASM32, GLSL, Delphi. GestaltGames: C++, C#, ActionScript, PHP. NTUU "KPI": Python, chalk and board, Ph. D. Synrc: Erlang, Javascript. Impuls: C++, Python, bash, pen and paper. Materialise: C++, Python, whiteboard occasionally. Also wordsandbuttons.online.
Updated on June 04, 2022Comments
-
Muhammad Asif almost 2 years
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?