[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: How to improve my summarizing code

William James

10/11/2015 7:21:00 AM

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.collection)
(define (summarize input)
(map
(^x (list (caar x) (apply + (map cadr x))))
(group-collection input :key car)))

gosh> (summarize '((c 7) (a 1) (a 3) (b 1) (b 10) (b 100)))
((c 7) (a 4) (b 111))

--
[W]e had enough employees who made more than 85 to fill all the openings. The
highest score that any of the blacks scored on the test was 11. The lowest
score that any black made on the test was 4. All four of those blacks went
into skilled-trades training.
https://archive.org/download/TheOldmanArchives/oldman29-...
1 Answer

William James

10/13/2015 1:02:00 AM

0

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

Portable Standard Lisp:

(load useful)

(de summarize (list)
(for
(with summary sum)
(in elt list)
(do
(setq sum (assoc (car elt) summary))
(if sum
(incr (second sum) (second elt))
(push elt summary)))
(returns summary)))

(summarize '((c 7) (a 1) (a 3) (b 1) (b 10) (b 100)))
===>
((b 111) (a 4) (c 7))

Shorter:

(de summarize (list)
(let (summary)
(while list
(let* ((elt (pop list))
(sum (assoc (car elt) summary)))
(if sum
(incr (second sum) (second elt))
(push elt summary))))
summary))