Rocksolid Light

News from da outaworlds

mail  files  register  groups  login

Message-ID:  

Your reasoning powers are good, and you are a fairly good planner.


comp / comp.lang.lisp / Re: Any way to collect all the values of a hash table more concisely ?

SubjectAuthor
o Re: Any way to collect all the values of a hash table more concisely ?B. Pym

1
Subject: Re: Any way to collect all the values of a hash table more concisely ?
From: B. Pym
Newsgroups: comp.lang.lisp
Organization: A noiseless patient Spider
Date: Fri, 16 Aug 2024 09:17 UTC
Path: eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail
From: Nobody447095@here-nor-there.org (B. Pym)
Newsgroups: comp.lang.lisp
Subject: Re: Any way to collect all the values of a hash table more concisely ?
Date: Fri, 16 Aug 2024 09:17:30 -0000 (UTC)
Organization: A noiseless patient Spider
Lines: 36
Message-ID: <v9n5f6$1cr85$1@dont-email.me>
MIME-Version: 1.0
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit
Injection-Date: Fri, 16 Aug 2024 11:17:30 +0200 (CEST)
Injection-Info: dont-email.me; posting-host="11ab68af5c40cbcfc2b0c32a89bdff20";
logging-data="1469701"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18P2rc4WZ8nB1nLBfptQ59Q"
User-Agent: XanaNews/1.18.1.6
Cancel-Lock: sha1:QwEvlW7qaj9iwohEVMjABCWi3Nk=
View all headers

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")))

1

rocksolid light 0.9.8
clearnet tor