rbb
rbb

Reputation: 999

Clojure - Adding Values in multiple vectors by index

I have 3 vectors [1 2 3] [4 5 6] [7 8 9. I want to add the vectors by indices ie return a vector

[(+ 1 4 7) (+ 2 5 8) (+ 3 6 9)] => [12 15 18]

I thought if doing something like this but I realise I'm not getting the vector out

(defn vec-adder [x y z]
  (loop [a 1]
    (when (< a (count x)
      (recur (+ (nth x a) (nth y a) (nth z a)) (+ a 1)))))

Any help would be much appreciated. Thanks.

Upvotes: 0

Views: 328

Answers (1)

Chris Murphy
Chris Murphy

Reputation: 6509

(mapv + [1 2 3] [4 5 6] [7 8 9])

+ is a function that can take any number of arguments (it is multi-arity).

Upvotes: 8

Related Questions