In short, 'reduce-list', is take a list of variable length, 'b',
below and reduce it if the (caar ls) and (caadr ls) are equal...this
is the first atom within the pair of consecutive sublists and if this
is true contruct a list, (list (caar ls) (+ (cadar ls) (cadadr ls)))
, and add second atom of the consective pairs. For example,
(reduce-list b) ==> ((4 3) (3 7) (2 1) (1 2) (0 1)). I can get it to
work for the first two terms without using recursion, produces (4 3),
but when I implement recursion it barfs. Could some one tell me what
I'm doing wrong because I know that I'm trying to do to much at once?
-Conrad
(define (reduce-list ls)
(cond ((null? ls) ls)
(else
(cond ((null? (cadr ls)) ls)
(else
(cond ((eq? (caar ls) (caadr ls))
(list (caar ls) (+ (cadar ls) (cadadr ls)))
(reduce-list (cdr ls)))
(else (list (car ls) (reduce-list (cdr ls)))))))))))
(define b '((4 1) (4 2) (3 3) (3 4) (2 1) (1 2) (0 1)))
(reduce-list b)
(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))
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 365 |
Nodes: | 16 (3 / 13) |
Uptime: | 24:40:01 |
Calls: | 7,748 |
Calls today: | 2 |
Files: | 12,888 |
Messages: | 5,740,133 |
Posted today: | 1 |