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

mats cronqvist <>
Wed Jan 21 17:58:53 CET 2009


Bjorn Gustavsson <> writes:

> On Wed, Jan 21, 2009 at 4:40 PM, mats cronqvist <> wrote:
>> Bjorn Gustavsson <> writes:
>>
>>>>  seems i've written this function at least a thousand times;
>>>>
>>>> keyfind(Key,N,List) ->
>>>>  {value,{Key,Val} = lists:keysearch(Key,N,List),
>>>>  Val.
>>>
>>> This version only works for tuples of size 2.
>>
>>  it was meant as an example, not an implementation proposal. i didn't
>>  balance the braces either :<
>
> Yes, but if the tuple has more than two elements, how do you know
> which field the caller is interested in? Do you assume that it always
> the element after the key? What is the caller is interested in several
> fields of the tuple?


  my point (if there was one) was that i write this function

keyfind(Key,List) ->
  {value,{Key,Val}} = lists:keysearch(Key,List),
  Val.

  again and again because a keyfind function should return a value of
  exit. if the tuple arity is > 2, it'll obviously have to return the
  whole yuple on success, but it should still exit on failure.

  alas, my example was both poorly chosen and buggy.

  mats



More information about the erlang-questions mailing list