Reputation: 173
I have a list of tuples looking e.g. like this:
[{apple, fruit},{pear, fruit},{tomato, vegetable}]
One of my functions is supposed to go through the list and return an element by key like this:
1> db:find(pear, Db).
{ok,fruit}
My function does this and looks like this:
find(Key, DbRef) -> [{ok, Element} || {Key1, Element} <- DbRef, Key =:= Key1].
But I also want it to return something like this:
2> db:find(cucumber, Db).
{error,unknown}
when the Key is not found in the list.
Is this possible??
Upvotes: 0
Views: 334
Reputation: 7836
This sounds simple:
db:find(Key,Proplist)-> case proplists:get_value(Key,Proplist) of undefined -> {error,unknown}; Value -> {ok,Value} end.
Upvotes: 0
Reputation: 426
Use lists:keyfind/3
or proplists:get_value/2,3
.
lists:keyfind/3
is the very best option for this task. It is a BIF and, as such, is written in C. It is far and away faster than the proplists
module or any other pure-erlang implementation. It's also capable of working with more complex tuples with keys in different positions (as would be the case if you had a list of records).
Using the lists
module:
{pear, fruit} = lists:keyfind(pear, 1, Db),
false = lists:keyfind(cucumber, 1, Db).
Using the proplists
module:
fruit = proplists:get_value(pear, Db),
undefined = proplists:get_value(cucumber, Db),
{error, instance} = proplists:get_value(cucumber, Db, {error, instance}).
Or even mix the two, with the proplists
-style keyfind
:
get_value(Key, List) -> get_value(Key, List, undefined).
get_value(Key, List, Default) ->
case lists:keyfind(Key, 1, List) of
false -> Default;
{Key, Value} -> Value
end.
Usage:
fruit = get_value(pear, Db),
undefined = get_value(cucumber, Db),
{error, instance} = get_value(cucumber, Db, {error, instance}).
Upvotes: 6
Reputation: 20916
You have to recursively step down the list looking at each element. If it has the right key then you return the value otherwise you call yourself recursively to look at the rest of the list. If you reach the end then you know that the element is not there and you return the {error,instance}
.
Upvotes: 1