, , , .
, . ( 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)
add-pairs(v1 acc)
else
return acc }
function add-pairs(v1) {
return add-pairs(v1,[])
}
var result = add-pairs([42 666 1447])
Peter source
share