Question

Inputting a vector I'd like to write a function that gives successive differences between elements. Ideally the function should input a vector x and parameter n that designates nth difference.

Sample in the form [x n]

Input 1: [16 10 8 6 4 2] 1 (1 for first difference)

Output 1: [-6 -2 -2 -2 -2]

Input 2: [16 10 8 6 4 2] 2

Output 2: [4 0 0 0 nil nil]

Symbolically here's what is going on for sample 2 (meant as illustration of idea, not Clojure code)

[a b c d e f] 2

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

Was it helpful?

Solution 2

Same as @Shlomi 's answer but with an optional step size parameter:

(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)))

OTHER TIPS

Here you go:

(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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top