lists:keyfind/3
またはを使用しproplists:get_value/2,3
ます。
lists:keyfind/3
このタスクに最適なオプションです。proplists
これはBIFであり、Cで記述されています。モジュールやその他のpure-erlang実装よりもはるかに高速です。また、さまざまな位置にキーを持つより複雑なタプルを操作することもできます(レコードのリストがある場合のように)。
例
lists
モジュールの使用:
{pear, fruit} = lists:keyfind(pear, 1, Db),
false = lists:keyfind(cucumber, 1, Db).
proplists
モジュールの使用:
fruit = proplists:get_value(pear, Db),
undefined = proplists:get_value(cucumber, Db),
{error, instance} = proplists:get_value(cucumber, Db, {error, instance}).
または、proplists
-styleを使用して2つを混合することもでき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.
使用法:
fruit = get_value(pear, Db),
undefined = get_value(cucumber, Db),
{error, instance} = get_value(cucumber, Db, {error, instance}).