GNU bug report logs -
#28753
25.3; Functions to get alist from hash table and vice versa
Previous Next
Reported by: Drew Adams <drew.adams <at> oracle.com>
Date: Mon, 9 Oct 2017 00:27:02 UTC
Severity: wishlist
Found in version 25.3
Done: Lars Ingebrigtsen <larsi <at> gnus.org>
Bug is archived. No further changes may be made.
Full log
View this message in rfc822 format
[Message part 1 (text/plain, inline)]
Drew Adams <drew.adams <at> oracle.com> schrieb am Mo., 9. Okt. 2017 um
02:27 Uhr:
> Dunno whether functions like these might be useful. I use something
> similar. If you think they're useful, consider adding them.
>
I think both are useful.
>
> (cl-defun alist-to-hash-table (alist &optional use-last-p
> &key (test 'eql) weakness (size 65)
> (rehash-size 1.5) (rehash-threshold
> 0.8))
> "Create and return a hash table created from ALIST.
> By default, if the same alist key is used in more than one alist entry
> then only the first entry is used for the hash table. Non-nil
> USE-LAST-P means override this to use only the last entry for a given
> key.
>
> See `make-hash-table' for the keyword arguments you can use and their
> default values."
> (let ((ht (make-hash-table :test test :weakness weakness :size size
> :rehash-size rehash-size :rehash-threshold
> rehash-threshold))
> key val)
> (dolist (key.val alist)
> (setq key (car key.val)
> val (cdr key.val))
> (when (or use-last-p (not (gethash key ht)))
>
This doesn't work if the value is nil. You need to use an uninterned symbol
or some other unique object, e.g.
(eq (gethash key ht #1='#:void) #1#)
> (puthash key val ht)))
> ht))
>
I'd personally make use-last-p another keyword argument, though.
>
> (defun hash-table-to-alist (hash-table)
> "Create and return an alist created from HASH-TABLE.
> The order of alist entries is the same as the order of hash-table
> entries (which normally is the order in which the entries were added
> to the table)."
> (let ((al ()))
> (maphash (lambda (key val) (push (cons key val) al)) hash-table)
> (nreverse al)))
>
>
Hmm, is the order guaranteed? I haven't found anything in the Emacs Lisp
manual about this, so maybe just leave out the parenthetical remark or say
that the order is unspecified?
[Message part 2 (text/html, inline)]
This bug report was last modified 3 years and 32 days ago.
Previous Next
GNU bug tracking system
Copyright (C) 1999 Darren O. Benham,
1997,2003 nCipher Corporation Ltd,
1994-97 Ian Jackson.