The following are two implementations of accumulate - n one that uses map and another that does not. However, both use accumulate procedure.
(define (accumulate op init lst)
(if (null? lst)
init
(op (car lst)
(accumulate op init
(cdr lst)))))
Implementation 1:
(define (accumulate-n op init seqs)
(if (null? (car seqs))
'()
(cons (accumulate op init (car seqs))
(accumulate-n op init (if (pair? (cdr seqs)) (cdr seqs) (list(cdr seqs)))))))
(accumulate-n + 0 (list (list 1) (list 4 5 6)))
Implementation 2:
(define (accumulate-n op init lst)
(define (accumulate-help lst)
(accumulate op init lst))
(map accumulate-help lst))
(accumulate-n + 0 (list (list 1 2 3) (list 4 5 6) (list 7 8 9)))
No comments:
Post a Comment