Different Way Forward

J, 15 9 7 bytes

Very easy. Takes depth and list as left and right arguments.

-~/\~&2

As an explicit definition without all the adverbial trickery, this reduces to

4 : '(2 -~/\ ])^:x y'
  • -~/\~&2 y – The forwards difference of y.
  • x -~/\~&2 y – The x-th forwards difference of y.

If I were to make a serious (i. e. non-golfed) definition of this function, I would probably do something like this:

(}. - }:) : ($:@[&0)

The monadic case computes the forward difference whereas the dyadic case computes the x-th forward difference.

Even simpler, but not exactly equal:

+/\inv

+/\ yields a vector of the sums of the prefixes of the argument. inv (defined as ^:_1) is a conjunction that inverses a verb. This works wherever J knows how to inverse a verb and for the case of +/\, J knows how to.


Python, 61 59 bytes

f=lambda n,L:n and f(n-1,[x-y for x,y in zip(L[1:],L)])or L

Here we perform the subtraction by zipping all but the last of the list with all but the first of the list. zip(L[1:],L) is equivalent to zip(L[1:],L[:-1]), due to zip's nature of taking the minimum length of the two lists:

>>> zip([1,2,3],[4,5])
[(1, 4), (2, 5)]

An alternative that's just as long (Python 2 only):

f=lambda n,L:n and f(n-1,map(int.__sub__,L[1:],L[:-1]))or L

Unfortunately Python 2 doesn't cut off the end of the list, so I can't do map(int.__sub__,L,L[1:]). Annoyingly, Python 3 does, but map no longer returns a list so this ends up being a byte more (60 bytes):

f=lambda n,L:n and f(n-1,list(map(int.__sub__,L[1:],L)))or L

However, if we allow the input to be the depth followed by the list like f(3, 2, 5, 6, 7, 5, 10, 25) (i.e. depth 3 and list [2, 5, 6, 7, 5, 10, 25]), then this is 56 bytes:

f=lambda n,*T:n and f(n-1,*map(int.__sub__,T[1:],T))or T

Here's another alternative that would really annoy anyone who saw this in production code (this one destroys the original list):

f=lambda n,L:n and f(n-1,[L[1]-L.pop(0)for _ in L[1:]])or L

Mathematica 23 57 23 bytes

Martin Büttner's suggestion, exploiting the listability of subtraction.

 Rest@#-Most@#&~Nest~##&

e.g.

Rest@# - Most@# &~Nest~## & @@ {{10, 18, -12, 4, 8, -3, -5, 67, 9, 14}, 4}

{-142, 55, 27, 41, -269, 397}


Rest@#-Most@# carries out the subtraction that yields differences.

Nest performs said operation the specified number of times, operating always on the most recent list.