On 3/27/2022, Robert L. wrote:
> (define b '((4 1) (4 2) (4 80) (3 3) (3 4) (2 1) (1 2) (0 1)))
>
> (define (reduce-list xs)
> (if (null? xs)
> '()
> (let ((k (caar xs)))
> (receive (these those)
> (span (lambda (ys) (equal? (car ys) k)) xs)
> (cons (list k (apply + (map cadr these)))
> (reduce-list those))))))
>
> (reduce-list b)
> ===>
> ((4 83) (3 7) (2 1) (1 2) (0 1))
Using pattern-matching.
Gauche Scheme:
(use util.match)
(define (kons xs accum)
(match `(,xs ,accum)
[((a b) ((c d) z ...)) (=> no)
(if (equal? a c)
(cons (list a (+ b d)) z)
(no))]
[(y z) (cons y z)]))
(define (reduce-list xs) (fold-right kons '() xs))
(define b '((4 1) (4 2) (4 80) (3 3) (3 4) (2 1) (1 2) (0 1)))