emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [PATCH] Add new function to test whether a key is present in a hash


From: Eric Abrahamsen
Subject: Re: [PATCH] Add new function to test whether a key is present in a hash table.
Date: Thu, 15 Feb 2018 15:35:22 -0800
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/27.0.50 (gnu/linux)

Drew Adams <address@hidden> writes:

>> Such a function is useful because in Emacs Lisp, 'gethash' cannot
>> return whether the key is present as in Common Lisp, and using
>> 'gethash' alone to test for presence is nontrivial.
>
> Glad to see this.  Everyone was coding their own (in Lisp).

+1

>> +While it might be tempting to use @code{gethash} to check whether a
>> +key is present in a hash table, keep in mind that you often need to
>> +distinguish between @var{key} being absent and @var{key} being mapped
>> +to @var{default}.  To easily distinguish between these two cases,
>> +there's another function to explicitly check whether a key is present:
>> +
>> address@hidden hash-table-contains-p key table
>> +This function looks up @var{key} in @var{table}; it returns @code{t}
>> +if @var{key} is present, and @code{nil} otherwise.  The associated
>> +value is ignored.
>
> 1. I don't think we need to say "The associated value is
> ignored".  Nothing suggests that it would be used in any way.
>
> 2. The function name should have `key' in it, I think.  Suggestion:
> `hash-table-contains-key-p' or even just `hash-table-key-p'.
>
> 3. Another possibility could be to return, as the true value,
> a cons of the value associated with the key.  IOW, instead
> of returning `t' we would return `(THE-VALUE)'.   If this
> is not particularly costly it might be a bit more useful.

I would really like to see a function that didn't require us to:

(and (hash-table-key-p "key" <table>) (gethash "key" <table>))

Ie, an all-in-one function (happy to see it implemented in elisp, a la
Stefan's solution) that gives us both pieces of information at once.
Drew's cons-cell seems like a good middle ground. We could even call it
`hash-table-get', to contrast with `gethash', and still have it accept
(and return) the optional DFLT argument.

Eric



reply via email to

[Prev in Thread] Current Thread [Next in Thread]