Clojure函数用于第一个差异,第二个差异,......,第n个差异

时间:2013-11-20 22:49:22

标签: clojure clojure-contrib

输入一个向量我想写一个能给出元素之间连续差异的函数。理想情况下,函数应输入一个向量x和参数n,它指定第n个差异。

以[x n]

形式的样本

输入1:[16 10 8 6 4 2] 1(第一个差异为1)

输出1:[ - 6 -2 -2 -2 -2]

输入2:[16 10 8 6 4 2] 2

输出2:[4 0 0 0 nil nil]

象征性地,这里是样本2的内容(意思是说明,而不是Clojure代码)

[a b c d e f] 2

[a-2b + c,b-2c + d,c-2d + e,d-2e + f]

2 个答案:

答案 0 :(得分:5)

你走了:

(def a [16 10 8 6 4 2])

(defn diff [a] 
  (map - (rest a) a))

(defn diff-n [a n]
  (nth (iterate diff a) n))

(diff-n a 1) ; => (-6 -2 -2 -2 -2)
(diff-n a 2) ; => (4 0 0 0)

答案 1 :(得分:1)

与@Shlomi的answer相同,但有一个可选的步长参数:

(defn diff
  ([a]
    (map - (next a) a))
  ([a step]
    (map - (nthnext a step) a)))

(defn nthdiff
  ([a n]
    (nth (iterate diff a) n))
  ([a n step]
    (nth (iterate #(diff % step) a) n)))