Search code examples
clojureclojure-contrib

Clojure function for first differences, second differences,...,nth differences


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]


Solution

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