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

Kostis Sagonas kostis@REDACTED
Thu Jan 22 12:58:14 CET 2009

James Hague wrote:
> 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.

Slightly unrelated to the above discussion but strictly speaking the 
above statement is not true.

lists:keysearch/3 nowhere insists that its third argument is a list of 
tuples.  Consequently, what lists:keysearch/3 does is to search for a 
tuple with a given key in a list of Erlang terms that may or may not 
contain tuples of size at least as big as the integer in its second 

For example, the following happily returns 'false' instead of throwing 
an exception (as many, perhaps naively, would expect it to).

   42> lists:keysearch(foo, 1, [3.14, gazonk]).

Also, the list does not have to be proper.

   43> lists:keysearch(foo, 1, [3.14, {foo,bar} | gazonk]).

Similarly, the function nowhere checks whether the element index is 
within the tuple bounds:

   44> lists:keysearch(foo, 42, [{foo,bar}]).

Bottom line: it's a useful but not particularly kosher function.


More information about the erlang-questions mailing list