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

Mikael Pettersson mikpe@REDACTED
Wed Jan 21 13:02:07 CET 2009


Richard Carlsson writes:
 > 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"

keyfind is the lighter-weight keysearch-done-right, and keysearch
returns false so keyfind should too.

 > 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).

The problem with that is that while technically sound it leads to a
plethora of function-specific 'no' values. So for programmer sanity
agreeing on a common 'no' value, e.g. 'false', is beneficial.

 > > 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.

My point is that 'no' is a normal operating condition for this
function (it combines query with lookup in a non-faulting way),
and thus 'error' is highly inappropriate. (And yes my example
was a bit off.)

As an old Lisp afficionado I don't mind using [] (NIL) as the
out-of-bands token, but I realize most Erlang programmers prefer
atoms instead, and in that domain 'false' seems appropriate.



More information about the erlang-questions mailing list