yeh
yeh

Reputation: 1506

How to add elements of the same index in two seqs together in Clojure

I have

[1 1 1 1 1]

and

[2 2 2 2 2]

I want

[3 3 3 3 3]

I tried

(for [x s1
      y s2
      :when (= (.indexOf s1 x) (.indexOf s2 y))]
   (+ x y))

It gives wrong result because .indexOf doesn't return its acctual index but search it using its value.

Any one can help?

Upvotes: 0

Views: 79

Answers (2)

mikera
mikera

Reputation: 106351

If you use core.matrix (link), then operators can be extended to work with vectors of numbers and you can just do:

(use 'clojure.core.matrix.operators)

(+ [1 1 1 1 1] [2 2 2 2 2])
=> [3 3 3 3 3]

In general, you should be looking a core.matrix if you are going to do a lot of work with vectors / matrices / multi-dimensional arrays in Clojure.

Upvotes: 1

mtyaka
mtyaka

Reputation: 8848

You can do it with map:

(map + [1 1 1 1 1] [2 2 2 2 2])
;; => (3 3 3 3 3)

Upvotes: 5

Related Questions