tags:

views:

119

answers:

3

If I had a N lists each of length M, how could I write a nice clean function to return a single list of length M, where each element is the sum of the corresponding elements in the N lists?

(starting to learn lisp - go easy!)

+8  A: 

This is a job for the map and apply functions. Here is a way to do it, with an EDIT suggested by Nathan Sanders:

(define (add-lists . more)
  (apply map + more))
Pillsy
Apply takes multiple arguments, only the last is a list, so you could get away with `(apply map + more)`
Nathan Sanders
Sorry - I was making some embarrassing mistakes. Thanks for your excellent answer!
ntimes
@Nathan: Cool. I didn't know that applied to Scheme's `apply`; I do most of my Lisping in CL.
Pillsy
+2  A: 

For a more matlab like syntax:

(define (piecewise func)
  (lambda more
    (apply map func more)))
(define pw piecewise)

((pw +) '(1 2 3 4 5) '(6 7 8 9 0))
((pw -) '(1 2 3 4 5) '(6 7 8 9 0))
((pw *) '(1 2 3 4 5) '(6 7 8 9 0))
((pw /) '(1 2 3 4 5) '(6 7 8 9 0.1))

outputs:

(7 9 11 13 5)
(-5 -5 -5 -5 5)
(6 14 24 36 0)
(1/6 2/7 3/8 4/9 50.0)
Davorak
+2  A: 

Just this works in MIT scheme.

 (map + '(1 2 3) '(4 5 6) '(7 8 9))
;Value 28: (12 15 18)
Fakrudeen