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

Richard Carlsson richardc@REDACTED
Wed Jan 21 12:44:37 CET 2009


Mikael Pettersson wrote:

>  > Only that I always wince at the mixing of 'false' with {...}. Since this
>  > is a new function, I'd prefer 'error' (to pick another atom that is
>  > frequently used in Erlang libraries).
> 
> Except that it's not actually an error to ask "search list L
> for a tuple T with value K in element N and return T, or tell
> me if none could be found". So I'd argue that 'false' is much
> more appropriate than 'error'.

I  tried to narrow it down to just one alternative suggestion, and
{ok,Value}|'error' is the convention used by dict:find. It seems
to depend on what you read into the name of the function: if the
name is "find" or "keyfind", aren't you expecting it to find the
element? You didn't use the "lookforsomethingthatmightnotbethere"
function. Anyhow, I wouldn't have suggested 'error' unless there
was some precedence for it. I prefer 'none' or 'not_found' for
this kind of return value, but consistency is also a good thing
(so maybe 'false' is still best).

> At least, _I_ don't want that to be an error, since that would
> require silly coding like:
> 1. ask if the element is there, but don't return it (query, boolean)
> 2. if it's there, get it (lookup, throws exn on failure not never here)
> when what one often wants is:
> 1. if the element is there, return it, otherwise return 'no'

Yes, but you don't use 1+2 for dict:find() just because it might
return the atom 'error', do you? I didn't suggest that keyfind
should throw an exception.

    /Richard



More information about the erlang-questions mailing list