[erlang-questions] lists:keyfind as an alternative to lists:keysearch

Bjorn Gustavsson <>
Wed Jan 21 14:37:35 CET 2009


On Tue, Jan 20, 2009 at 4:15 PM, James Hague <> wrote:
> I would like to propose the addition of lists:keyfind/3, which is
> identical in structure to lists:keysearch/3, except that it returns
> either 'false' or the found tuple, with no additional wrapping of the
> result.  This can be trivially added to the lists module:
>
>   keyfind(K, N, L) ->
>      case keysearch(K, N, L) of
>         {_, Tuple} -> Tuple;
>         X -> X
>      end.
>

I have now done a prototype implementation of keyfind/3 as BIF.
I did on small change to the semantics. I implemented it to be equivalent
to

keyfind1(Key, N, [H|T]) when element(N, H) =:= Key -> H;
keyfind1(Key, N, [H|T]) -> keyfind1(Key, N, T);
keyfind1(Key, N, []) -> false.

rather than

keyfind2(Key, N, [H|T]) when element(N, H) == Key -> H;
keyfind2(Key, N, [H|T]) -> keyfind2(Key, N, T);
keyfind2(Key, N, []) -> false.

(keyfind1/3 uses '=:=', keyfind2/3 uses '==').

They give the same result in most cases expect when
integers is compared to floats as in:

3> t:keyfind1(42, 1, [{42.0,a}]).
false
4> t:keyfind2(42, 1, [{42.0,a}]).
{42.0,a}

I think that it was a historical accident that lists:keysearch/3 and
lists:keymember/3 use
'==' rather than '=:=' and that we should not repeat that mistake
lists:keyfind/3.

/Bjorn
-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list