jamiei
jamiei

Reputation: 2036

Idiomatic way to sum multiple vectors in Clojure

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

Upvotes: 2

Views: 2474

Answers (2)

Ankur
Ankur

Reputation: 33657

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

Upvotes: 0

liwp
liwp

Reputation: 6926

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

Upvotes: 4

Related Questions