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?
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]).
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.
The module proplists
contains get_value/2
, which should be what you want.
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.
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