kazuwal
kazuwal

Reputation: 1091

Multiply nested pairs of list values in Clojure

What I am ultimately trying to do is multiply two vectors together and return a vector of the same size eg:

[6 7 8 9 10] * [0 1 3 1 0] => [0 7 24 9 0]

I was attempting to do something like:

(partition 2 (interleave [6 7 8 9 10] [0 1 3 1 0])) => ((6 0) (7 1) (8 3) (9 1) (10 0))

... then multiply each nested list value and use flatten to get:

(0 7 24 9 0)

but I cant figure out how I could multiply nested list values?

Upvotes: 1

Views: 366

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91534

Map takes multiple sequences and a function to combine each member with the corresponding member of the other sequences.

user> (map * [6 7 8 9 10] [0 1 3 1 0])
(0 7 24 9 0)
user> (mapv * [6 7 8 9 10] [0 1 3 1 0])
[0 7 24 9 0]

in this case it calls * on the first number from each list, then on the second from each list and so on, building a seq of the output. If you would prefer the output in a vector mapv is convenient.

Upvotes: 3

Related Questions