Sujet : Re: Any way to collect all the values of a hash table more concisely ?
De : No_spamming (at) *nospam* noWhere_7073.org (B. Pym)
Groupes : comp.lang.lispDate : 06. Jul 2024, 00:09:09
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v69qu1$3f6ps$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
So this new version works as intended:
(defun cluster-by (fn list &aux (clusters (make-hash-table)) (result nil))
(mapcar #'(lambda (x) (push x (gethash (funcall fn x) clusters))) list)
(maphash #'(lambda (key value) (push value result)) clusters)
(sort result #'< :key #'(lambda (x) (length (car x)))))
Um, sorry:
(defun cluster-by (fn list &aux (clusters (make-hash-table)) (result nil))
(mapcar #'(lambda (x) (push x (gethash (funcall fn x) clusters))) list)
(maphash #'(lambda (key value) (push value result)) clusters)
(sort result #'< :key #'(lambda (x) (funcall fn (car x)))))
^^^^^^^^^^
"lambda" is a macro that expands to (function (lambda ...)).
So instead of
#'(lambda
he ought to use
(lambda
The poster prefers #'lambda because he prefers ugliness.
Common Lisp is used by those who want code to be as
hideous as possible.
Gauche Scheme
(define (cluster-by fn lst)
(let ((clusters (make-hash-table 'equal?)))
(dolist (k lst)
(hash-table-push! clusters (fn k) k))
(hash-table-values clusters)))
(cluster-by string-length '("a" "b" "abc" "bc" "a" "abcd" "e" "fg"))
===>
(("abcd") ("e" "a" "b" "a") ("fg" "bc") ("abc"))