3

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]

sunspots
  • 1,047
  • 13
  • 29

2 Answers2

6

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)
Shlomi
  • 4,708
  • 1
  • 23
  • 32
  • How would you include a step size with this code? Whereby differences of elements b steps apart are given. – sunspots Nov 21 '13 at 01:46
  • I dont understand what you mean, could you try to explain better? – Shlomi Nov 21 '13 at 08:31
  • If I input a step size of 1 with input 2 from above, I'll get back output 2. However, changing the step size to 2 for input 2 will output [4 0]. If I have l elements in the input vector, then I should expect my output to have l-n*Abs(s) elements. In the case of input 2 that is l=6, n=2, s=2, 2 elements are output and collected in a vector. – sunspots Nov 21 '13 at 19:30
1

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)))
Community
  • 1
  • 1
omiel
  • 1,573
  • 13
  • 16