Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure-How to add successive pairs in vector?

Trying to write a recursive function that adds successive pairs in a vector.

[1 2 3 4] => [3 5 7]

Pretty much stuck and this is what I have currently:

(def tmp  [ 1 2 3 4])

user> (map #(+ (second %) (first %)) (partition-all 2 tmp ))

This is wrong as it adds just the pairs and not successive pairs. I get[3 7] instead of [3 5 7]

like image 575
AaronGarcia Avatar asked Dec 02 '22 18:12

AaronGarcia


2 Answers

Partition takes an extra argument specifying how far to step forward between each partition.

(map #(apply + %) (partition 2 1 [1 2 3 4 5])) =>

(3 5 7 9)

like image 192
noisesmith Avatar answered Dec 21 '22 04:12

noisesmith


Here is another possible solution:

(def tmp [1 2 3 4])

(map + tmp (rest tmp))
like image 37
Shlomi Avatar answered Dec 21 '22 04:12

Shlomi