Sujet : Re: Any way to collect all the values of a hash table more concisely ?
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lispDate : 16. Aug 2024, 11:17:30
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v9n5f6$1cr85$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
Leandro Rios wrote:
Leandro Rios escribió:
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)))))
^^^^^^^^^^
newLISP
(macro (aalt! Alist Key Func Default)
(if (assoc Key Alist)
(setf (assoc Key Alist) (list ($it 0) (Func ($it 1))))
(push (list Key (Func Default)) Alist)))
(macro (apush! Alist Key Val)
(aalt! Alist Key (curry cons Val) '()))
(define (group-by func lst (alist '()))
(dolist (x lst) (apush! alist (func x) x))
alist)
(group-by length '("a" "b" "abc" "bc" "a" "abcd" "e" "fg"))
===>
((4 ("abcd")) (2 ("fg" "bc")) (3 ("abc")) (1 ("e" "a" "b" "a")))