B. Pym
2024-07-05 22:09:09 UTC
(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)))))
(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)))))
(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)))))
^^^^^^^^^^
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"))