2

Problem: I've got a collection of vectors or lists which I would like to find an idiomatic way to sum onto an existing vector possibly with uneven sized vectors. Contrived example showing the setup:

=>(def collated-list [2 3 4 5 6 7 8])
=>(def lists-to-add (partition-all 3 collatedlist))
=>(def base-list [1 1 1])

I'd like the result to sum the broken down collated lists onto the base-list, for example, the first item would be 1 + 2 + 5 + 8 and so on.

What I've tried: I've tried a map and a for loop in couple of different ways but I seem to encounter either problems with Lazy Sequencing or problems of trying to add an Integer to a Vector.

These are my first experiments with Clojure so it's almost certainly me mis-understanding functional iteration here.

Thanks

liwp
  • 6,746
  • 1
  • 27
  • 39
jamiei
  • 2,006
  • 3
  • 20
  • 28
  • See also the recent [Changing map behaviour in Clojure](http://stackoverflow.com/questions/9033678/changing-map-behaviour-in-clojure) question which deals with `map`-with-padding in the general case (i.e. with an arbitrary function, number of lists and padding element). – Michał Marczyk Feb 09 '12 at 14:17

2 Answers2

4

First of all, it'll be much easier if lists-to-add contains lists of even length, so use partition instead of partition-all:

(def lists-to-add (partition 3 3 '(0 0) collated-list))

And then you can do the summing with map and recursion:

(defn sum-lists [base-lists lists-to-add]
    (reduce #(map + %1 %2) base-list lists-to-add))
liwp
  • 6,746
  • 1
  • 27
  • 39
0
; List of list
(def lst (partition 5 (range 200)))

; Base list
(def base [1 1 1 1 1])

; Sum operation
(apply map (fn [& args] (apply + args) ) base lst)
Ankur
  • 33,367
  • 2
  • 46
  • 72
  • This won't work properly with uneven sized vectors. Besides, you could just use + instead of (fn [& args] (apply + args) ) – Roman Bataev Feb 08 '12 at 16:13