开发者

Vector addition of lists

开发者 https://www.devze.com 2022-12-22 19:37 出处:网络
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 ea开发者_C百科ch element is the sum of the corresponding elements in the N lists

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 ea开发者_C百科ch element is the sum of the corresponding elements in the N lists?

(starting to learn lisp - go easy!)


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


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)


Just this works in MIT scheme.

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

精彩评论

暂无评论...
验证码 换一张
取 消