Deutsch English Français Italiano |
<v5cces$124eb$1@dont-email.me> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!feeds.phibee-telecom.net!2.eu.feeder.erje.net!feeder.erje.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: "B. Pym" <No_spamming@noWhere_7073.org> Newsgroups: comp.lang.lisp Subject: Re: How to improve my summarizing code Date: Mon, 24 Jun 2024 18:04:16 -0000 (UTC) Organization: A noiseless patient Spider Lines: 60 Message-ID: <v5cces$124eb$1@dont-email.me> References: <v5al3j$nuim$1@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Injection-Date: Mon, 24 Jun 2024 20:04:16 +0200 (CEST) Injection-Info: dont-email.me; posting-host="6992755104a3d7a4ecae094c19f92520"; logging-data="1118667"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19QAS5YKRFoFc5murEyEPTi" User-Agent: XanaNews/1.18.1.6 Cancel-Lock: sha1:JtR5Muy1JCIL0ml/PS9L7XXgRnw= Bytes: 2585 On 6/23/2024, B. Pym wrote: > Wade Humeniuk wrote: > > > Yeah, but I do not worry about it, much, at the beginning. Here > > is another, it seems easier to think in the morning > > > > (defun summarize (list) > > (let ((summary nil)) > > (map nil (lambda (elt) > > (let ((sum (find (first elt) summary :test #'eql :key #'first))) > > (if sum > > (incf (second sum) (second elt)) > > (push elt summary)))) > > list) > > summary)) > > > > and its loop version > > > > (defun summarize (list) > > (loop with summary = nil > > for elt in list > > for sum = (find (first elt) summary :test #'eql :key #'first) > > if sum do (incf (second sum) (second elt)) > > else do (push elt summary) > > finally (return summary))) > > > > CL-USER 2 > (summarize '((c 7) (a 1) (a 3) (b 1) (b 10) (b 100))) > > ((B 111) (A 4) (C 7)) > > Gauche Scheme > > (use gauche.sequence) ;; group-sequence > > (define (summarize alist) > (map > (lambda(xs) (list (caar xs) (fold + 0 (map cadr xs)))) > (group-sequence alist :key car))) > > (summarize '((c 7) (a 1) (a 3) (b 1) (b 10) (b 100))) > ===> > ((c 7) (a 4) (b 111)) Another way: (use util.match) (define (summarize assoclist) (define tree (make-tree-map)) (for-each (match-lambda [(key val) (tree-map-update! tree key (cut + <> val) 0)]) assoclist) (tree-map->alist tree)) (summarize '((c 7) (a 1) (a 3) (b 1) (b 10) (b 100))) ===> ((a . 4) (b . 111) (c . 7))