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

James Hague james.hague@REDACTED
Tue Jan 20 16:15:42 CET 2009

I proposed this several years ago, but now that there seems to be
quite a bit of momentum for improving the language and implementation,
I'm revising it.  It's a library tweak, so no formal EEP.  If anyone
wants a real EEP, let me know.

lists:keysearch/3 is used for searching a list of tuples.  It returns
two possible values:

* 'false' if a tuple containing the desired key is not found
* {value, Tuple} if a tuple is found.

Wrapping the result in a tagged tuple is not needed.  It causes
pointless memory allocation and code to check the result.  In fact,
it's more efficient to check for this pattern:

   {_, Tuple}

than to include the "value" atom.

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

But ideally it would be a BIF (like lists:keysearch) to avoid
construction of the tagged tuple.  At the moment, association lists
and the "key" functions are one of the best alternatives to
lightweight dictionaries.  With this proposed change, they'd be even
lighter weight and simpler to use.

More information about the erlang-questions mailing list