Clojure -How to add consecutive pairs to a vector?

Trying to write a recursive function that adds consecutive pairs to a vector.

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

Pretty stuck, and this is what I have now:

(def tmp  [ 1 2 3 4])

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

This is incorrect because it only adds pairs, not consecutive pairs. I get [3 7]instead[3 5 7]

+4
source share
3 answers

Here is another possible solution:

(def tmp [1 2 3 4])

(map + tmp (rest tmp))
+8
source

The section contains an additional argument indicating how far to go forward between each section.

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

(3 5 7 9)

+7
source

, , , .

, . ( acc ) .

(defn add-pairs [v1]
  (loop [the-list v1  acc []]
    (if   (next the-list) ;; checks wether there more than 1 left in the-list
      (recur (rest the-list ) 
             (conj  acc (+ (first the-list) (second the-list))))
     acc)))

? [1 2 3 4] v1. :

the-list <- [1 2 3 4]
acc []

(+ (first the-list) (second the-list) . recur , (rest the-list) , 3 ( ). :

the-list <- [2 3 4]
acc [3]

:

the-list <- [3 4]
acc [3 5]

the-list <- [4]
acc [3 5 7]

if , else ( , ).

. , . . if-, .

, . () (cdr ).

The loop / repeat form in clojure is very nice, but many other languages ​​lack this syntax. A very classic solution is to have two functions: one recursive, which executes the loop, and one with the same name, but the other arity, which performs battery initialization. Simplified in code than to explain, so here is some compiled java-like syntax:

function add-pairs(v1 acc) {
   if (cond)
      //do stuff to v1 and acc
      add-pairs(v1 acc)
   else 
      return acc }

function add-pairs(v1) {
   return add-pairs(v1,[])
}

var result = add-pairs([42 666 1447]) 
+1
source

All Articles