Forward difference: Difference between revisions

m
(Nimrod -> Nim)
m (→‎{{header|Wren}}: Minor tidy)
 
(84 intermediate revisions by 39 users not shown)
Line 1:
{{task|Arithmetic operations}}
 
Provide code that produces a list of numbers which is the n-th order forward difference, given a non-negative integer (specifying the order) and a list of numbers.
;Task:
The first-order forward difference of a list of numbers (A) is a new list (B) where B<sub>n</sub> = A<sub>n+1</sub> - A<sub>n</sub>. List B should have one fewer element as a result.
TheProvide second-ordercode forwardthat differenceproduces a list of Anumbers willwhich beis the same&nbsp; as<big>n<sup>th</sup></big> the first-&nbsp;order forward difference, given a non-negative integer (specifying the order) and a list of Bnumbers.
 
That new list will have two fewer elements than A and one less than B.
 
The first-order forward difference of a list of numbers &nbsp; <big>'''A'''</big> &nbsp; is a new list &nbsp; <big>'''B'''</big>, &nbsp; where &nbsp; <big><b>B</b><sub>n</sub> = <b>A</b><sub>n+1</sub> - <b>A</b><sub>n</sub></big>.
 
List &nbsp; <big>'''B'''</big> &nbsp; should have one fewer element as a result.
 
The second-order forward difference of &nbsp; <big>'''A'''</big> &nbsp; will be:
<pre>
tdefmodule Diff do
def forward(arr,i\\1) do
forward(arr,[],i)
end
 
def forward([_|[]],diffs,i) do
if i == 1 do
IO.inspect diffs
else
forward(diffs,[],i-1)
end
end
 
def forward([val1|[val2|vals]],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
</pre>
The same as the first-order forward difference of &nbsp; <big>'''B'''</big>.
 
That new list will have two fewer elements than &nbsp; <big>'''A'''</big> &nbsp; and one less than &nbsp; <big>'''B'''</big>.
 
The goal of this task is to repeat this process up to the desired order.
 
For a more formal description, see the related &nbsp; [http://mathworld.wolfram.com/ForwardDifference.html Mathworld article].
 
 
Algorithmic options:
;Algorithmic options:
*Iterate through all previous forward differences and re-calculate a new array each time.
* Iterate through all previous forward differences and re-calculate a new array each time.
*Use this formula (from [[wp:Forward difference|Wikipedia]]):
* Use this formula (from [[wp:Forward difference|Wikipedia]]):
:<math>\Delta^n [f](x)= \sum_{k=0}^n {n \choose k} (-1)^{n-k} f(x+k)</math>
<big><big>
:([[Pascal's Triangle]] may be useful for this option)
::: <math>\Delta^n [f](x)= \sum_{k=0}^n {n \choose k} (-1)^{n-k} f(x+k)</math>
</big></big>
::: ([[Pascal's Triangle]] &nbsp; may be useful for this option.)
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V dif = s -> enumerate(s[1..]).map2((i, x) -> x - @s[i])
F difn(s, n) -> [Int]
R I n != 0 {difn(dif(s), n - 1)} E s
 
V s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
 
L(i) 10
print(difn(s, i))</syntaxhighlight>
 
{{out}}
<pre>
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
[54, -40, 22, 17, 13, -73, 100, -32]
[-94, 62, -5, -4, -86, 173, -132]
[156, -67, 1, -82, 259, -305]
[-223, 68, -83, 341, -564]
[291, -151, 424, -905]
[-442, 575, -1329]
[1017, -1904]
[-2921]
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.containers.Vectors;
Line 64 ⟶ 123:
Print(Diff(A, 10));
print(Diff(A, 0));
end Forward_Difference;</langsyntaxhighlight>
{{out}}
<pre>
Line 79 ⟶ 138:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68">main:(
MODE LISTREAL = [1:0]REAL;
 
Line 99 ⟶ 158:
printf((list fmt,s,$";"l$))
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 112 ⟶ 171:
( 1017.0,-1904.0);
(-2921.0);
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% calculate forward differences %
 
% sets elements of B to the first order forward differences of A %
% A should have bounds 1 :: n, B should have bounds 1 :: n - 1 %
procedure FirstOrderFDifference ( integer array A( * )
; integer array B( * )
; integer value n
) ;
for i := 2 until n do B( i - 1 ) := A( i ) - A( i - 1 );
 
integer array v ( 1 :: 10 );
integer array diff( 1 :: 9 );
integer vPos, length;
 
% construct the initial values array %
vPos := 1;
for i := 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 do begin
v( vPos ) := i;
vPos := vPos + 1
end for_i ;
% calculate and show the differences %
i_w := 5; % set output format %
length := 10;
for order := 1 until length - 1 do begin
FirstOrderFDifference( v, diff, length );
length := length - 1;
write( order, ": " ); for i := 1 until length do writeon( diff( i ) );
for i := 1 until length do v( i ) := diff( i )
end for_order
end.</syntaxhighlight>
{{out}}
<pre>
1 : -43 11 -29 -7 10 23 -50 50 18
2 : 54 -40 22 17 13 -73 100 -32
3 : -94 62 -5 -4 -86 173 -132
4 : 156 -67 1 -82 259 -305
5 : -223 68 -83 341 -564
6 : 291 -151 424 -905
7 : -442 575 -1329
8 : 1017 -1904
9 : -2921
</pre>
 
Line 117 ⟶ 221:
{{works with|Dyalog APL}}{{trans|J}}
 
<langsyntaxhighlight lang="apl"> list ← 90 47 58 29 22 32 55 5 55 73
fd ← {⍺=0:⍵⋄(⍺-1)∇(1↓⍵)-(¯1↓⍵)}
Line 125 ⟶ 229:
2 fd list
54 ¯40 22 17 13 ¯73 100 ¯32</langsyntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
 
<syntaxhighlight lang="applescript">-- forwardDifference :: Num a => [a] -> [a]
on forwardDifference(xs)
zipWith(my subtract, xs, rest of xs)
end forwardDifference
 
 
-- nthForwardDifference :: Num a => Int -> [a] -> [a]
on nthForwardDifference(xs, i)
|index|(iterate(forwardDifference, xs), 1 + i)
end nthForwardDifference
 
 
-------------------------- TEST ---------------------------
on run
script show
on |λ|(xs, i)
((i - 1) as string) & " -> " & showList(xs)
end |λ|
end script
unlines(map(show, ¬
take(10, ¬
iterate(forwardDifference, ¬
{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}))))
end run
 
 
-------------------- GENERIC FUNCTIONS --------------------
 
-- Just :: a -> Maybe a
on Just(x)
-- Constructor for an inhabited Maybe (option type) value.
-- Wrapper containing the result of a computation.
{type:"Maybe", Nothing:false, Just:x}
end Just
 
-- Nothing :: Maybe a
on Nothing()
-- Constructor for an empty Maybe (option type) value.
-- Empty wrapper returned where a computation is not possible.
{type:"Maybe", Nothing:true}
end Nothing
 
 
-- index (!!) :: [a] -> Int -> Maybe a
-- index (!!) :: Gen [a] -> Int -> Maybe a
-- index (!!) :: String -> Int -> Maybe Char
on |index|(xs, i)
if script is class of xs then
repeat with j from 1 to i
set v to |λ|() of xs
end repeat
if missing value is not v then
Just(v)
else
Nothing()
end if
else
if length of xs < i then
Nothing()
else
Just(item i of xs)
end if
end if
end |index|
 
 
-- intercalate :: String -> [String] -> String
on intercalate(delim, xs)
set {dlm, my text item delimiters} to ¬
{my text item delimiters, delim}
set str to xs as text
set my text item delimiters to dlm
str
end intercalate
 
 
-- iterate :: (a -> a) -> a -> Gen [a]
on iterate(f, x)
script
property v : missing value
property g : mReturn(f)'s |λ|
on |λ|()
if missing value is v then
set v to x
else
set v to g(v)
end if
return v
end |λ|
end script
end iterate
 
 
-- length :: [a] -> Int
on |length|(xs)
set c to class of xs
if list is c or string is c then
length of xs
else
(2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite)
end if
end |length|
 
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
 
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
 
 
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
-- 2nd class handler function lifted into 1st class script wrapper.
if script is class of f then
f
else
script
property |λ| : f
end script
end if
end mReturn
 
 
-- showList :: [a] -> String
on showList(xs)
"[" & intercalate(", ", map(my str, xs)) & "]"
end showList
 
 
-- str :: a -> String
on str(x)
x as string
end str
 
 
-- subtract :: Num -> Num -> Num
on subtract(x, y)
y - x
end subtract
 
 
-- take :: Int -> [a] -> [a]
-- take :: Int -> String -> String
on take(n, xs)
set c to class of xs
if list is c then
if 0 < n then
items 1 thru min(n, length of xs) of xs
else
{}
end if
else if string is c then
if 0 < n then
text 1 thru min(n, length of xs) of xs
else
""
end if
else if script is c then
set ys to {}
repeat with i from 1 to n
set v to |λ|() of xs
if missing value is v then
return ys
else
set end of ys to v
end if
end repeat
return ys
else
missing value
end if
end take
 
 
-- unlines :: [String] -> String
on unlines(xs)
-- A single string formed by the intercalation
-- of a list of strings with the newline character.
set {dlm, my text item delimiters} to ¬
{my text item delimiters, linefeed}
set s to xs as text
set my text item delimiters to dlm
s
end unlines
 
 
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
on zipWith(f, xs, ys)
set lng to min(|length|(xs), |length|(ys))
if 1 > lng then return {}
set xs_ to take(lng, xs) -- Allow for non-finite
set ys_ to take(lng, ys) -- generators like cycle etc
set lst to {}
tell mReturn(f)
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs_, item i of ys_)
end repeat
return lst
end tell
end zipWith</syntaxhighlight>
{{Out}}
<pre>0 -> [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
1 -> [-43, 11, -29, -7, 10, 23, -50, 50, 18]
2 -> [54, -40, 22, 17, 13, -73, 100, -32]
3 -> [-94, 62, -5, -4, -86, 173, -132]
4 -> [156, -67, 1, -82, 259, -305]
5 -> [-223, 68, -83, 341, -564]
6 -> [291, -151, 424, -905]
7 -> [-442, 575, -1329]
8 -> [1017, -1904]
9 -> [-2921]</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">; element-wise subtraction of two blocks. e.g.
; vsub [1 2 3] [1 2 3] ; [0 0 0]
vsub: function [u v][
map couple u v 'pair -> pair\0 - pair\1
]
 
differences: function [block][
order: attr "order"
if order = null -> order: 1
loop 1..order 'n -> block: vsub block drop block
return block
]
 
print differences .order: 4 [90.5 47 58 29 22 32 55 5 55 73.5]
print differences [1 2 3 4 5 6 7]</syntaxhighlight>
 
{{out}}
 
<pre>156.5 -67 1 -82 259 -304.5
-1 -1 -1 -1 -1 -1</pre>
 
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276470.html#276470 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % diff("2,3,4,3",1)
MsgBox % diff("2,3,4,3",2)
MsgBox % diff("2,3,4,3",3)
Line 145 ⟶ 507:
}
Return list
}</syntaxhighlight>
}</lang>
 
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
if (p<1) {p = 1};
Line 168 ⟶ 530:
{
print diff($0, p);
}</langsyntaxhighlight>
 
Using Pascal's triangle:
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
if (p<1) {p = 1};
Line 198 ⟶ 560:
{
print diff($0, p);
}</langsyntaxhighlight>
 
{{out}}
Line 222 ⟶ 584:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM A(9)
A() = 90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0
PRINT "Original array: " FNshowarray(A())
Line 251 ⟶ 613:
a$ += STR$(a(i%)) + ", "
NEXT
= LEFT$(LEFT$(a$))</langsyntaxhighlight>
{{out}}
<pre>
Line 259 ⟶ 621:
Forward diff 9: -2921
</pre>
 
 
=={{header|BQN}}==
 
Left argument is the order, right argument is the array.
 
<syntaxhighlight lang="bqn">FDiff ← {{-˜´˘2↕𝕩}⍟𝕨 𝕩}
 
•Show 1 FDiff 90‿47‿58‿29‿22‿32‿55‿5‿55‿73
•Show 2 FDiff 90‿47‿58‿29‿22‿32‿55‿5‿55‿73</syntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <string.h>
#include <stdio.h>
Line 299 ⟶ 671:
 
return 0;
}</langsyntaxhighlight>
 
Use method with Pascal triangle, binomial coefficients are pre-computed
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int* binomCoeff(int n) {
Line 336 ⟶ 708:
printf("\n");
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 366 ⟶ 738:
} while ((sequence = ForwardDifference(sequence)).Any());
}
}</langsyntaxhighlight>
{{out}}
<pre>90, 47, 58, 29, 22, 32, 55, 5, 55, 73
Line 385 ⟶ 757:
which is then called several times for calculating n-th order forward difference.
No error checking is implemented.
<langsyntaxhighlight lang="cpp">#include <vector>
#include <iterator>
#include <algorithm>
Line 495 ⟶ 867:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 509 ⟶ 881:
 
===Using Standard Template Library===
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <numeric>
Line 526 ⟶ 898:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 541 ⟶ 913:
Usually one will not want the intermediate results,
in which case the following is sufficient:
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <numeric>
Line 555 ⟶ 927:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 562 ⟶ 934:
 
===Using Pascal's Triangle===
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <algorithm>
Line 577 ⟶ 949:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 584 ⟶ 956:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn fwd-diff [nums order]
(nth (iterate #(map - (next %) %) nums) order))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
forward_difference = (arr, n) ->
# Find the n-th order forward difference for arr using
Line 600 ⟶ 972:
for n in [0..arr.length]
console.log n, forward_difference arr, n
</syntaxhighlight>
</lang>
{{out}}
<pre>> coffee forward_difference.coffee
Line 615 ⟶ 987:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun forward-difference (list)
(mapcar #'- (rest list) list))
 
Line 621 ⟶ 993:
(setf list (copy-list list))
(loop repeat n do (map-into list #'- (rest list) list))
(subseq list 0 (- (length list) n)))</langsyntaxhighlight>
 
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">T[] forwardDifference(T)(in T[] data, in int level) pure nothrow
in {
assert(level >= 0 && level < data.length);
Line 644 ⟶ 1,015:
foreach (immutable level; 0 .. data.length)
forwardDifference(data, level).writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]
Line 659 ⟶ 1,030:
===Alternative Version===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.array;
 
auto forwardDifference(Range)(Range d, in int level) pure {
Line 671 ⟶ 1,042:
foreach (immutable level; 0 .. data.length)
forwardDifference(data, level).writeln;
}</langsyntaxhighlight>
 
===Using Vector Operations===
forwardDifference mutates the array in-place (same output):
<langsyntaxhighlight lang="d">import std.stdio;
 
T[] forwardDifference(T)(T[] s, in int n) pure nothrow @nogc {
Line 686 ⟶ 1,057:
foreach (immutable level; 0 .. A.length)
forwardDifference(A.dup, level).writeln;
}</langsyntaxhighlight>
 
===Short Functional Version===
Same output:
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.range;
 
Line 699 ⟶ 1,070:
a[n - 1][0 .. $ - 1])[0 .. $] }(D)
.take(D.length));
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">List forwardDifference(List _list) {
for (int i = _list.length - 1; i > 0; i--) {
_list[i] = _list[i] - _list[i - 1];
}
 
_list.removeRange(0, 1);
return _list;
}
 
void mainAlgorithms() {
List _intList = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
 
for (int i = _intList.length - 1; i >= 0; i--) {
List _list = forwardDifference(_intList);
print(_list);
}
}</syntaxhighlight>
 
{{out}}
<pre>
Restarted application in 1,143ms.
flutter: [-43, 11, -29, -7, 10, 23, -50, 50, 18]
flutter: [54, -40, 22, 17, 13, -73, 100, -32]
flutter: [-94, 62, -5, -4, -86, 173, -132]
flutter: [156, -67, 1, -82, 259, -305]
flutter: [-223, 68, -83, 341, -564]
flutter: [291, -151, 424, -905]
flutter: [-442, 575, -1329]
flutter: [1017, -1904]
flutter: [-2921]
flutter: []
</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Forward_difference#Pascal Pascal].
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
/** Single step. */
def forwardDifference(seq :List) {
Line 734 ⟶ 1,141:
> require(r1 == nthForwardDifference2(sampleData, n))
> println(r1)
> }</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
Using the built-in function '''iterate''' which, given a function f and n, returns the function f°f°f....°f .
<syntaxhighlight lang="lisp">
(define (Δ-1 list)
(for/list ([x (cdr list)] [y list]) (- x y)))
 
(define (Δ-n n) (iterate Δ-1 n))
 
((Δ-n 9) '(90 47 58 29 22 32 55 5 55 73))
→ (-2921)
</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Diff do
def forward(list,i\\1) do
forward(list,[],i)
end
def forward([_],diffs,1), do: IO.inspect diffs
def forward([_],diffs,i), do: forward(diffs,[],i-1)
def forward([val1,val2|vals],diffs,i) do
forward([val2|vals],diffs++[val2-val1],i)
end
end
 
Enum.each(1..9, fn i ->
Diff.forward([90, 47, 58, 29, 22, 32, 55, 5, 55, 73],i)
end)</syntaxhighlight>
 
{{out}}
<pre>
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
[54, -40, 22, 17, 13, -73, 100, -32]
[-94, 62, -5, -4, -86, 173, -132]
[156, -67, 1, -82, 259, -305]
[-223, 68, -83, 341, -564]
[291, -151, 424, -905]
[-442, 575, -1329]
[1017, -1904]
[-2921]
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(forward_difference).
-export([difference/1, difference/2]).
 
Line 754 ⟶ 1,203:
io:format("Initial: ~p~n",[?TEST_DATA]),
[io:format("~3b: ~p~n",[N,difference(?TEST_DATA,N)]) || N <- lists:seq(0,length(?TEST_DATA))],
ok.</langsyntaxhighlight>
{{out}}
<pre>80> forward_difference:task().
Line 771 ⟶ 1,220:
ok
</pre>
 
=={{header|F_Sharp|F#}}==
Straightforward recursive solution
<syntaxhighlight lang="fsharp">let rec ForwardDifference input n =
match n with
| _ when input = [] || n < 0 -> [] // If there's no more input, just return an empty list
| 0 -> input // If n is zero, we're done - return the input
| _ -> ForwardDifference // otherwise, recursively difference..
(input.Tail // All but the first element
|> Seq.zip input // tupled with itself
|> Seq.map (fun (a, b) -> b-a) // Subtract the i'th element from the (i+1)'th
|> Seq.toList) (n-1) // Make into a list and do an n-1 difference on it</syntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel math math.vectors sequences ;
IN: rosetacode
 
Line 782 ⟶ 1,243:
dup 0 <=
[ drop ] [ [ 1-order ] times ] if ;
</syntaxhighlight>
</lang>
( scratchpad ) { 90.5 47 58 29 22 32 55 5 55 73.5 } 4 n-order .
{ 156.5 -67 1 -82 259 -304.5 }
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: forward-difference
dup 0
?do
Line 801 ⟶ 1,262:
: test a 10 9 forward-difference bounds ?do i ? loop ;
 
test</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE DIFFERENCE
IMPLICIT NONE
 
Line 823 ⟶ 1,285:
WRITE (*,*) b(1:arraysize-n)
END SUBROUTINE Fdiff
END MODULE DIFFERENCE</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">PROGRAM TEST
 
USE DIFFERENCE
Line 837 ⟶ 1,299:
END DO
 
END PROGRAM TEST</langsyntaxhighlight>
{{out}}
<pre>
Line 851 ⟶ 1,313:
</pre>
 
=={{headerHeader|F_Sharp|F#FreeBASIC}}==
<syntaxhighlight lang="freebasic">function forward_difference( a() as uinteger ) as uinteger ptr
Straightforward recursive solution
dim as uinteger ptr b = allocate( sizeof(uinteger) * (ubound(a)-1) )
<lang fsharp>let rec ForwardDifference input n =
for i as uinteger = 0 to ubound(a)-1
match n with
*(b+i) = a(i+1)-a(i)
| _ when input = [] || n < 0 -> [] // If there's no more input, just return an empty list
next i
| 0 -> input // If n is zero, we're done - return the input
return b
| _ -> ForwardDifference // otherwise, recursively difference..
end function
(input.Tail // All but the first element
 
|> Seq.zip input // tupled with itself
dim as uinteger a(0 to 15) = {2, 3, 5, 7, 11, 13, 17, 19,_
|> Seq.map (fun (a, b) -> b-a) // Subtract the i'th element from the (i+1)'th
|> Seq.toList) (n-1) 23, //29, Make31, into37, a41, list43, and47, do an n-1 difference on it</lang>53}
dim as uinteger i
 
dim as uinteger ptr b = forward_difference( a() )
 
for i = 0 to ubound(a)-1
print *(b+i)
next i
</syntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 881 ⟶ 1,351:
}
return a[:len(a)-ord]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 890 ⟶ 1,360:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">forwardDifference xs:: =Num zipWitha (-)=> (tail[a] xs)-> xs[a]
forwardDifference = tail >>= zipWith (-)
 
nthForwardDifference xs:: nNum a => iterate[a] forwardDifference-> xsInt !!-> n[a]
nthForwardDifference = (!!) . iterate forwardDifference
 
main :: IO ()
> take 10 (iterate forwardDifference [90, 47, 58, 29, 22, 32, 55, 5, 55, 73])
main =
[[90,47,58,29,22,32,55,5,55,73],
mapM_ print $
[-43,11,-29,-7,10,23,-50,50,18],
take 10 (iterate forwardDifference [90, 47, 58, 29, 22, 32, 55, 5, 55, 73])</syntaxhighlight>
[54,-40,22,17,13,-73,100,-32],
{{Out}}
[-94,62,-5,-4,-86,173,-132],
<pre>[90,47,58,29,22,32,55,5,55,73]
[156,-67,1,-82,259,-305],
[-22343,6811,-8329,341-7,10,23,-564]50,50,18]
[29154,-15140,42422,17,13,-905]73,100,-32]
[-94,62,-5,-4,-86,173,-132]
[-442,575,-1329],
[156,-67,1,-82,259,-305]
[1017,-1904],
[-223,68,-83,341,-564]
[-2921]]</lang>
[291,-151,424,-905]
[-442,575,-1329]
[1017,-1904]
[-2921]</pre>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n=10, list(n)
 
list = ( 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 )
Line 918 ⟶ 1,394:
ENDDO
 
END</langsyntaxhighlight>
{{out}}
<pre>0 90 47 58 29 22 32 55 5 55 73
Line 932 ⟶ 1,408:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure main(A) # Compute all forward difference orders for argument list
every order := 1 to (*A-1) do showList(order, fdiff(A, order))
end
Line 948 ⟶ 1,424:
every writes(!L," ")
write()
end</langsyntaxhighlight>
 
{{out|A sample run}}
Line 968 ⟶ 1,444:
Standard IDL library function <tt>TS_diff(X,k,[/double])</tt>:
 
<langsyntaxhighlight lang="idl">print,(x = randomu(seed,8)*100)
15.1473 58.0953 82.7465 16.8637 97.7182 59.7856 17.7699 74.9154
print,ts_diff(x,1)
Line 975 ⟶ 1,451:
-18.2967 -90.5341 146.737 -118.787 -4.08316 99.1613 0.000000 0.000000
print,ts_diff(x,3)
72.2374 -237.271 265.524 -114.704 -103.244 0.000000 0.000000 0.000000</langsyntaxhighlight>
 
=={{header|J}}==
Of the many ways to code this in J, a particularly concise solution is:
<langsyntaxhighlight lang="j">fd=: 2&(-~/\)</langsyntaxhighlight>
 
Alternatively, to reduce the number of J primitives, use:
<langsyntaxhighlight lang="j">fd=: }. - }: ^:</langsyntaxhighlight>
 
(which is also elegant, because the open-ended power conjunction reads like "to the power of anything").
 
For example:
<syntaxhighlight lang ="j"> list =: 90 47 58 29 22 32 55 5 55 73 NB. Some numbers
 
1 fd list
Line 993 ⟶ 1,469:
2 fd list
54 _40 22 17 13 _73 100 _32</langsyntaxhighlight>
 
J is array oriented, so you can even ask for more than one forward difference at a time (i.e. <tt>N</tt> can be a list, instead of a single number):
<langsyntaxhighlight lang="j"> 1 2 3 fd list NB. First, second, and third forward differences (simultaneously)
43 _11 29 7 _10 _23 50 _50 _18
54 _40 22 17 13 _73 100 _32 0
Line 1,012 ⟶ 1,488:
1017 _1904 0 0 0 0 0 0 0 0
2921 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java">import java.util.Arrays;
public class FD {
public static void main(String args[]) {
Line 1,042 ⟶ 1,518:
return a;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,052 ⟶ 1,528:
null
[90.0, 47.0, 58.0, 29.0, 22.0, 32.0, 55.0, 5.0, 55.0, 73.0]
 
=={{header|JavaScript}}==
 
===ES6===
 
<syntaxhighlight lang="javascript">(() => {
'use strict';
 
// forwardDifference :: Num a => [a] -> [a]
const forwardDifference = xs =>
zipWith(subtract)(xs)(tail(xs));
 
 
// nthForwardDifference :: Num a => [a] -> Int -> [a]
const nthForwardDifference = xs =>
index(iterate(forwardDifference)(xs)).Just;
 
 
//----------------------- TEST ------------------------
// main :: IO ()
const main = () =>
unlines(
take(10)(
iterate(forwardDifference)(
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
)
).map((x, i) => justifyRight(2)('x')(i) + (
' -> '
) + JSON.stringify(x))
);
 
 
//----------------- GENERIC FUNCTIONS -----------------
 
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
 
 
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
 
 
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
 
 
// index (!!) :: [a] -> Int -> Maybe a
// index (!!) :: Generator (Int, a) -> Int -> Maybe a
// index (!!) :: String -> Int -> Maybe Char
const index = xs => i => {
const s = xs.constructor.constructor.name;
return 'GeneratorFunction' !== s ? (() => {
const v = xs[i];
return undefined !== v ? Just(v) : Nothing();
})() : Just(take(i)(xs), xs.next().value);
};
 
 
// iterate :: (a -> a) -> a -> Gen [a]
const iterate = f =>
function*(x) {
let v = x;
while (true) {
yield(v);
v = f(v);
}
};
 
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => n > s.length ? (
s.padStart(n, c)
) : s;
 
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
 
 
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => (
Array.isArray(xs) ? (
xs
) : xs.split('')
).map(f);
 
 
// subtract :: Num -> Num -> Num
const subtract = x =>
y => y - x;
 
 
// tail :: [a] -> [a]
const tail = xs =>
// A new list consisting of all
// items of xs except the first.
0 < xs.length ? xs.slice(1) : [];
 
 
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
 
 
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
 
 
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f => xs => ys => {
const
lng = Math.min(length(xs), length(ys)),
[as, bs] = [xs, ys].map(take(lng));
return Array.from({
length: lng
}, (_, i) => f(as[i])(
bs[i]
));
};
 
// MAIN ---
return main();
})();</syntaxhighlight>
 
{{Out}}
<pre>0 -> [90,47,58,29,22,32,55,5,55,73]
1 -> [-43,11,-29,-7,10,23,-50,50,18]
2 -> [54,-40,22,17,13,-73,100,-32]
3 -> [-94,62,-5,-4,-86,173,-132]
4 -> [156,-67,1,-82,259,-305]
5 -> [-223,68,-83,341,-564]
6 -> [291,-151,424,-905]
7 -> [-442,575,-1329]
8 -> [1017,-1904]
9 -> [-2921]</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># If n is a non-negative number and if input is
# a (possibly empty) array of numbers,
# emit an array, even if the input list is too short:
Line 1,062 ⟶ 1,712:
elif n == 1 then . as $in | [range(1;length) | $in[.] - $in[.-1]]
else ndiff(1) | ndiff(n-1)
end;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">def s: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
 
range(0;12) as $i | (s|ndiff($i))</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -c -n -f forward-difference.jq
[90,47,58,29,22,32,55,5,55,73]
[-43,11,-29,-7,10,23,-50,50,18]
Line 1,080 ⟶ 1,730:
[-2921]
[]
[]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Using the built-in <code>diff</code> function, which returns the 1st forward difference:
 
<lang julia>ndiff(A, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1))</lang>
<syntaxhighlight lang="julia">ndiff(A::Array, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1))
 
s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
println.(collect(ndiff(s, i) for i in 0:9))</syntaxhighlight>
 
{{out}}
<pre>julia> s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
julia> [ndiff(s, i) for i in 0:9]
[54, -40, 22, 17, 13, -73, 100, -32]
10-element Array{Any,1}:
[-94, 62, -5, -4, -86, 173, -132]
[90,47,58,29,22,32,55,5,55,73]
[156, -4367,11 1, -2982,-7,10,23 259, -50,50,18305]
[54,-40223,22,17,13 68, -7383,100 341, -32564]
[291, -151, 424, -905]
[-94,62,-5,-4,-86,173,-132]
[-442, 575, -1329]
[156,-67,1,-82,259,-305]
[1017, -1904]
[-223,68,-83,341,-564]
[-2921]</pre>
[291,-151,424,-905]
[-442,575,-1329]
[1017,-1904]
[-2921]</pre>
 
=={{header|K4}}==
<syntaxhighlight lang ="k4">fd:1_-':</langsyntaxhighlight>
 
To compute the ''n''th forward difference, call as:
<syntaxhighlight lang ="k4">n fd/</langsyntaxhighlight>
 
In order to obtain all intermediate results, call as:
<syntaxhighlight lang ="k4">n fd\</langsyntaxhighlight>
 
{{out|Examples}}
Line 1,116 ⟶ 1,769:
3 fd\1 2 4 7 11 16
(1 2 4 7 11 16;1 2 3 4 5;1 1 1 1;0 0 0)</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
fun forwardDifference(ia: IntArray, order: Int): IntArray {
if (order < 0) throw IllegalArgumentException("Order must be non-negative")
if (order == 0) return ia
val size = ia.size
if (size == 0) return ia // same empty array
if (order >= size) return intArrayOf() // new empty array
var old = ia
var new = old
var count = order
while (count-- >= 1) {
new = IntArray(old.size - 1)
for (i in 0 until new.size) new[i] = old[i + 1] - old[i]
old = new
}
return new
}
 
fun printArray(ia: IntArray) {
print("[")
for (i in 0 until ia.size) {
print("%5d".format(ia[i]))
if (i < ia .size - 1) print(", ")
}
println("]")
}
 
fun main(args: Array<String>) {
val ia = intArrayOf(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)
for (order in 0..ia.size) {
val fd = forwardDifference(ia, order)
print("%2d".format(order) + ": ")
printArray(fd)
}
}</syntaxhighlight>
 
{{out}}
<pre>
0: [ 90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
1: [ -43, 11, -29, -7, 10, 23, -50, 50, 18]
2: [ 54, -40, 22, 17, 13, -73, 100, -32]
3: [ -94, 62, -5, -4, -86, 173, -132]
4: [ 156, -67, 1, -82, 259, -305]
5: [ -223, 68, -83, 341, -564]
6: [ 291, -151, 424, -905]
7: [ -442, 575, -1329]
8: [ 1017, -1904]
9: [-2921]
10: []
</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{def fdiff
{lambda {:l}
{A.new
{S.map {{lambda {:l :i} {- {A.get {+ :i 1} :l} {A.get :i :l}} } :l}
{S.serie 0 {- {A.length :l} 2}}}}}}
-> fdiff
 
{def disp
{lambda {:l}
{if {A.empty? {A.rest :l}}
then else {let { {:l {fdiff :l}} } {br}:l {disp :l}}}}}
-> disp
 
{def L {A.new 90 47 58 29 22 32 55 5 55 73}}
-> L
 
{disp {L}}
->
[-43,11,-29,-7,10,23,-50,50,18]
[54,-40,22,17,13,-73,100,-32]
[-94,62,-5,-4,-86,173,-132]
[156,-67,1,-82,259,-305]
[-223,68,-83,341,-564]
[291,-151,424,-905]
[-442,575,-1329]
[1017,-1904]
[-2921]
</syntaxhighlight>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">#!/usr/bin/lasso9
define forwardDiff(values, order::integer=1) => {
Line 1,133 ⟶ 1,870:
local(data = (:90, 47, 58, 29, 22, 32, 55, 5, 55, 73))
with x in generateSeries(0, #data->size-1)
do stdoutnl(#x + ': ' + forwardDiff(#data, #x))</langsyntaxhighlight>
{{out}}
<pre>0: array(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)
Line 1,147 ⟶ 1,884:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to fwd.diff :l
if empty? :l [output []]
if empty? bf :l [output []]
Line 1,158 ⟶ 1,895:
 
show nth.fwd.diff 9 [90 47 58 29 22 32 55 5 55 73]
[-2921]</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function dif(a, b, ...)
if(b) then return b-a, dif(b, ...) end
end
function dift(t) return {dif(unpack(t))} end
print(unpack(dift{1,3,6,10,15}))</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
Function Diff(a()) get an array by value (a shallow copy)
<syntaxhighlight lang="m2000 interpreter">
Form 80, 40
Module Forward_difference {
Print $(0,6) ' 6 characters column
Dim a(), b()
a()=(90,47,58,29,22,32,55,5,55,73)
Function Diff(a()) {
for i=0 to len(a())-2: a(i)=a(i+1)-a(i):Next i
Dim a(len(a())-1) ' redim one less
=a()
}
Print "Original:","",a()
b()=a() ' copy a() to b()
k=1
While len(b())>1 {
b()=Diff(b()) ' copy returned array to b()
Print "Difference ";k;":",b()
k++
}
}
Forward_difference
 
</syntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Original: 90 47 58 29 22 32 55 5 55 73
Difference 1: -43 11 -29 -7 10 23 -50 50 18
Difference 2: 54 -40 22 17 13 -73 100 -32
Difference 3: -94 62 -5 -4 -86 173 -132
Difference 4: 156 -67 1 -82 259 -305
Difference 5: -223 68 -83 341 -564
Difference 6: 291 -151 424 -905
Difference 7: -442 575 -1329
Difference 8: 1017 -1904
Difference 9: -2921
</pre >
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function:
<langsyntaxhighlight Mathematicalang="mathematica">i={3,5,12,1,6,19,6,2,4,9};
Differences[i]</langsyntaxhighlight>
{{out|gives back}}
<langsyntaxhighlight Mathematicalang="mathematica">{2, 7, -11, 5, 13, -13, -4, 2, 5}</langsyntaxhighlight>
The n<sup>th</sup> difference can be done as follows:
<langsyntaxhighlight Mathematicalang="mathematica">i={3,5,12,1,6,19,6,2,4,9};
Differences[i,n]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
Line 1,182 ⟶ 1,958:
X is the list of numbers,
n is the order of the forward difference.
<langsyntaxhighlight MATLABlang="matlab">Y = diff(X,n);</langsyntaxhighlight>
 
{{out}} 1st order forward difference.
Line 1,192 ⟶ 1,968:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">ldiff(u, n) := block([m: length(u)], for j thru n do u: makelist(u[i + 1] - u[i], i, 1, m - j), u);</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx*************************************************************
* Forward differences
* 18.08.2012 Walter Pachl derived from Rexx
Line 1,228 ⟶ 2,004:
Say n ol
End
End</langsyntaxhighlight>
Output is the same as for Rexx
 
=={{header|Nial}}==
Define forward difference for order 1
<langsyntaxhighlight lang="nial">fd is - [rest, front]</langsyntaxhighlight>
 
{{out}} forward difference of 4th order
<langsyntaxhighlight lang="nial">b := 90 47 58 29 22 32 55 5 55 73
4 fold fd b
= 156 -67 1 -82 259 -305</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc dif(s: seq[int]): seq[int] =
result = newSeq[int](s.len-1)
for i, x in s[10..<s.high]:
result[i] = xs[i+1] - s[i]
 
proc difn(s,: seq[int]; n: int): seq[int] =
if n > 0: difn(dif(s), n-1)
else: s
 
const s = @[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
echo difn(s, 0)
echo difn(s, 1)
echo difn(s, 2)</langsyntaxhighlight>
{{out}}
<pre>@[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
Line 1,261 ⟶ 2,037:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class Test {
Line 1,298 ⟶ 2,074:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let rec forward_difference = function
a :: (b :: _ as xs) ->
b - a :: forward_difference xs
Line 1,312 ⟶ 2,088:
xs
else
nth_forward_difference (pred n) (forward_difference xs)</langsyntaxhighlight>
 
{{out}}
Line 1,318 ⟶ 2,094:
# nth_forward_difference 9 [90; 47; 58; 29; 22; 32; 55; 5; 55; 73];;
- : int list = [-2921]
</pre>
 
=={{header|Oforth}}==
 
<syntaxhighlight lang="oforth">: forwardDiff(l) l right(l size 1 -) l zipWith(#-) ;
: forwardDiffN(n, l) l #[ forwardDiff dup println ] times(n) ;</syntaxhighlight>
{{out}}
<pre>
10 [ 90, 47, 58, 29, 22, 32, 55, 5, 55, 73] forwardDiffN
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
[54, -40, 22, 17, 13, -73, 100, -32]
[-94, 62, -5, -4, -86, 173, -132]
[156, -67, 1, -82, 259, -305]
[-223, 68, -83, 341, -564]
[291, -151, 424, -905]
[-442, 575, -1329]
[1017, -1904]
[-2921]
[]
</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">fd(v)=vector(#v-1,i,v[i+1]-v[i]);</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">Program ForwardDifferenceDemo(output);
 
procedure fowardDifference(list: array of integer);
Line 1,349 ⟶ 2,144:
begin
fowardDifference(a);
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./ForwardDifference
Line 1,364 ⟶ 2,159:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub dif {
my @s = @_;
map { $s[$_+1] - $s[$_] } 0 .. $#s-1
}
 
@a = qw<90 47 58 29 22 32 55 5 55 73>;
sub difn {
while (@a) { printf('%6d', $_) for @a = dif @a; print "\n" }</syntaxhighlight>
my ($n, @s) = @_;
{{out}}
@s = dif @s foreach 1..$n;
<pre> -43 11 -29 -7 10 23 -50 50 18
@s
54 -40 22 17 13 -73 100 -32
}</lang>
-94 62 -5 -4 -86 173 -132
156 -67 1 -82 259 -305
-223 68 -83 341 -564
291 -151 424 -905
-442 575 -1329
1017 -1904
-2921</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
{{works with|Rakudo Star|2010-07}}
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<p>Here we use signature matching to bind both an entire array and a version missing the head.
<span style="color: #008080;">function</span> <span style="color: #000000;">fwd_diff_n</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">order</span><span style="color: #0000FF;">)</span>
The Z- operator is a zip metaoperator with a minus to subtract the two lists pairwise.
<span style="color: #7060A8;">assert</span><span style="color: #0000FF;">(</span><span style="color: #000000;">order</span><span style="color: #0000FF;"><</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
It's almost a shame to define difn, since the series and subscript are hardly longer than the call itself would be, and arguably more self-documenting than the name of the function would be.
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<lang perl6>sub dif(@array [$, *@tail]) { @tail Z- @array }
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">order</span> <span style="color: #008080;">do</span>
sub difn($array, $n) { ($array, &dif ... *)[$n] }</lang>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]-</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">90</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">47</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">58</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">29</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">22</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">32</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">55</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">55</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">73</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">9</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">fwd_diff_n</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{-43,11,-29,-7,10,23,-50,50,18}
{54,-40,22,17,13,-73,100,-32}
{-94,62,-5,-4,-86,173,-132}
{156,-67,1,-82,259,-305}
{-223,68,-83,341,-564}
{291,-151,424,-905}
{-442,575,-1329}
{1017,-1904}
{-2921}
</pre>
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php"><?php
 
function forwardDiff($anArray, $times = 1) {
Line 1,427 ⟶ 2,254:
}
}</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
L = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73],
foreach(I in 1..L.length-1)
println([d=I,diffi(L,I)])
end,
nl,
% All differences (a sublist to save space)
println(alldiffs(L[1..6])),
nl.
 
% Difference of the list
diff(L) = Diff =>
Diff = [L[I]-L[I-1] : I in 2..L.length].
 
% The i'th list difference
diffi(L,D) = Diff =>
Diff1 = L,
foreach(_I in 1..D)
Diff1 := diff(Diff1)
end,
Diff = Diff1.
 
% all differences
alldiffs(L) = Diffs =>
Diffs1 = [],
Diff = L,
foreach(_I in 1..L.length-1)
Diff := diff(Diff),
Diffs1 := Diffs1 ++ [Diff]
end,
Diffs = Diffs1.</syntaxhighlight>
 
{{out}}
<pre>[d = 1,[-43,11,-29,-7,10,23,-50,50,18]]
[d = 2,[54,-40,22,17,13,-73,100,-32]]
[d = 3,[-94,62,-5,-4,-86,173,-132]]
[d = 4,[156,-67,1,-82,259,-305]]
[d = 5,[-223,68,-83,341,-564]]
[d = 6,[291,-151,424,-905]]
[d = 7,[-442,575,-1329]]
[d = 8,[1017,-1904]]
[d = 9,[-2921]]
 
[[-43,11,-29,-7,10],[54,-40,22,17],[-94,62,-5],[156,-67],[-223]]</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de fdiff (Lst)
(mapcar - (cdr Lst) Lst) )
 
(for (L (90 47 58 29 22 32 55 5 55 73) L (fdiff L))
(println L) )</langsyntaxhighlight>
{{out}}
<pre>(90 47 58 29 22 32 55 5 55 73)
Line 1,448 ⟶ 2,321:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Forward differences. */ /* 23 April 2010 */
differences: procedure options (main);
Line 1,470 ⟶ 2,343:
 
end differences;
</syntaxhighlight>
</lang>
 
=={{header|Plain English}}==
<syntaxhighlight lang="plainenglish">To add a fraction to some fraction things:
Allocate memory for a fraction thing.
Put the fraction into the fraction thing's fraction.
Append the fraction thing to the fraction things.
 
To create some fraction things:
Add 90-1/2 to the fraction things.
Add 47/1 to the fraction things.
Add 58/1 to the fraction things.
Add 29/1 to the fraction things.
Add 22/1 to the fraction things.
Add 32/1 to the fraction things.
Add 55/1 to the fraction things.
Add 5/1 to the fraction things.
Add 55/1 to the fraction things.
Add 73-1/2 to the fraction things.
 
To find the difference of some fraction things:
If the fraction things' count is less than 2, exit.
Get a fraction thing from the fraction things.
Loop.
If the fraction thing's next is nil, remove the fraction thing from the fraction things; destroy the fraction thing; exit.
Put the fraction thing's next's fraction minus the fraction thing's fraction into the fraction thing's fraction.
Put the fraction thing's next into the fraction thing.
Repeat.
 
To find the difference of some fraction things given an order:
If a counter is past the order, exit.
Find the difference of the fraction things.
Repeat.
 
A fraction thing is a thing with a fraction.
 
An order is a number.
 
To run:
Start up.
Create some fraction things.
Write "Original list:" on the console.
Show the fraction things.
Find the difference of the fraction things given 4.
Write "Order 4 forward difference:" on the console.
Show the fraction things.
Destroy the fraction things.
Wait for the escape key.
Shut down.
 
To show some fraction things:
Get a fraction thing from the fraction things.
Loop.
If the fraction thing is nil, write "" on the console; exit.
Write "" then the fraction thing's fraction on the console without advancing.
If the fraction thing's next is not nil, write ", " on the console without advancing.
Put the fraction thing's next into the fraction thing.
Repeat.</syntaxhighlight>
{{out}}
<pre>
Original list:
90-1/2, 47, 58, 29, 22, 32, 55, 5, 55, 73-1/2
Order 4 forward difference:
156-1/2, -67, 1, -82, 259, -304-1/2
</pre>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">define forward_difference(l);
lvars res = [], prev, el;
if l = [] then
Line 1,492 ⟶ 2,429:
endfor;
res;
enddefine;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<math>\Delta^n [f](x)= \sum_{k=0}^n \left ({\prod_{i=1}^k \frac{n-k+i}{i}}\right ) (-1)^{n-k} f(x+k)</math>
<langsyntaxhighlight PowerShelllang="powershell">function Forward-Difference( [UInt64] $n, [Array] $f )
{
$flen = $f.length
Line 1,517 ⟶ 2,454:
}
 
Forward-Difference 2 1,2,4,5</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure forward_difference(List a())
If ListSize(a()) <= 1
ClearList(a()): ProcedureReturn
Line 1,574 ⟶ 2,511:
EndIf
 
</syntaxhighlight>
</lang>
{{out}}
<pre>1 [43,-11,29,7,-10,-23,50,-50,-18]
Line 1,588 ⟶ 2,525:
 
=={{header|Python}}==
===Python 2===
<lang python>>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]
<syntaxhighlight lang="python">>>> dif = lambda s: [x-s[i] for i,x in enumerate(s[1:])]
>>> # or, dif = lambda s: [x-y for x,y in zip(s[1:],s)]
>>> difn = lambda s, n: difn(dif(s), n-1) if n else s
Line 1,611 ⟶ 2,549:
[-442, 575, -1329],
[1017, -1904],
[-2921]]</langsyntaxhighlight>
 
===Python 3===
Defining functions for first order and nth order forward difference:
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Forward difference'''
 
 
from itertools import islice
from operator import sub
 
 
# forwardDifference :: Num a => [a] -> [a]
def forwardDifference(xs):
'''1st order forward difference of xs.
'''
return [sub(*x) for x in zip(xs[1:], xs)]
 
 
# nthForwardDifference :: Num a => [a] -> Int -> [a]
def nthForwardDifference(xs):
'''Nth order forward difference of xs.
'''
return index(iterate(forwardDifference)(xs))
 
 
# ------------------------- TEST --------------------------
# main :: IO ()
def main():
'''Nth order forward difference.'''
 
xs = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
 
print('9th order forward difference of:')
print(xs)
print('')
print(
' -> ' + repr(nthForwardDifference(xs)(9))
)
 
print('\nSuccessive orders of forward difference:')
print(unlines([
str(i) + ' -> ' + repr(x) for i, x in
enumerate(take(10)(
iterate(forwardDifference)(xs)
))
]))
 
 
# ------------------- GENERIC FUNCTIONS -------------------
 
# index (!!) :: [a] -> Int -> a
def index(xs):
'''Item at given (zero-based) index.'''
return lambda n: None if 0 > n else (
xs[n] if (
hasattr(xs, "__getitem__")
) else next(islice(xs, n, None))
)
 
 
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
 
 
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
return lambda xs: (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
 
 
# unlines :: [String] -> String
def unlines(xs):
'''A single string formed by the intercalation
of a list of strings with the newline character.
'''
return '\n'.join(xs)
 
 
# MAIN ---
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>9th order forward difference of:
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
 
-> [-2921]
 
Successive orders of forward difference:
0 -> [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
1 -> [-43, 11, -29, -7, 10, 23, -50, 50, 18]
2 -> [54, -40, 22, 17, 13, -73, 100, -32]
3 -> [-94, 62, -5, -4, -86, 173, -132]
4 -> [156, -67, 1, -82, 259, -305]
5 -> [-223, 68, -83, 341, -564]
6 -> [291, -151, 424, -905]
7 -> [-442, 575, -1329]
8 -> [1017, -1904]
9 -> [-2921]</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ times
[ [] swap behead
swap witheach
[ tuck dip [ - join ] ]
drop ] ] is f-diff ( [ n --> [ )
 
' [ 90 47 58 29 22 32 55 5 55 73 ]
 
dup size times
[ dup i^
dup echo say ": "
f-diff echo cr ]
drop</syntaxhighlight>
 
{{out}}
 
<pre>0: [ 90 47 58 29 22 32 55 5 55 73 ]
1: [ -43 11 -29 -7 10 23 -50 50 18 ]
2: [ 54 -40 22 17 13 -73 100 -32 ]
3: [ -94 62 -5 -4 -86 173 -132 ]
4: [ 156 -67 1 -82 259 -305 ]
5: [ -223 68 -83 341 -564 ]
6: [ 291 -151 424 -905 ]
7: [ -442 575 -1329 ]
8: [ 1017 -1904 ]
9: [ -2921 ]
</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">forwarddif <- function(a, n) {
if ( n == 1 )
a[2:length(a)] - a[1:length(a)-1]
Line 1,634 ⟶ 2,716:
 
print(forwarddif(v, 9))
print(fdiff(v, 9))</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,650 ⟶ 2,732:
(nth-forward-difference 9 '(90 47 58 29 22 32 55 5 55 73))
;; -> '(-2921)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo Star|2010-07}}
<p>Here we use signature matching to bind both an entire array and a version missing the head.
The Z- operator is a zip metaoperator with a minus to subtract the two lists pairwise.
It's almost a shame to define difn, since the series and subscript are hardly longer than the call itself would be, and arguably more self-documenting than the name of the function would be.
<syntaxhighlight lang="raku" line>sub dif(@array [$, *@tail]) { @tail Z- @array }
sub difn($array, $n) { ($array, &dif ... *)[$n] }</syntaxhighlight>
 
=={{header|REXX}}==
===Versionno 1error checking===
UsesThe REXX version uses the same (input) numbers (for the default) as the &nbsp; '''Ada''' &nbsp; example.
<br>Half the program was dedicated to validating the input.
<br>This version allows a specification of the vector and/or which ''order'' to process.
<lang rexx>/*REXX program to compute the forward difference of a list of numbers.*/
/* ┌───────────────────────────────────────────────────────────────────┐
│ /\ n n n-k │
│ {delta} / \ n [ƒ] (x) ≡ Σ Ç ∙ (-1) ∙ ƒ(x+k) │
│ /____\ k=0 k │
│ │
│ {n=order} {Ç=comb or binomial coeff.} │
└───────────────────────────────────────────────────────────────────┘*/
numeric digits 100 /*ensure enough accuracy. */
arg numbers ',' ord /*input: x1 x2 x3 x4 ... ,ORD */
if numbers=='' then numbers='90 47 58 29 22 32 55 5 55 73' /*default?*/
w=words(numbers) /*set W to # of numbers in list.*/
 
This version allows a specification of the list of numbers and/or which &nbsp; ''order'' &nbsp; to process.
do i=1 for w /*validate input (valid numbers?)*/
<syntaxhighlight lang="rexx">/*REXX program computes the forward difference of a list of numbers. */
@.i=word(numbers,i) /*assign the next # in the list. */
numeric digits 100 /*ensure enough accuracy (decimal digs)*/
if \datatype(@.i,'N') then call ser @.i "isn't a valid number"
parse arg e ',' N @.i=@.i/1 /*normalizeget thea #,list: prettify theε1 ε2 ε3 ε4 ··· , order #*/
if e=='' then e=90 47 58 29 22 32 55 5 55 73 /*Not specified? Then use the default.*/
end /*i*/
#=words(e) /*# is the number of elements in list.*/
/*═════════════════════════════════════════process the (optional) input.*/
if w==0 then call ser 'no /* [↓] assign list numbers wereto @ specified'array.*/
do i=1 for #; @.i=word(e, i)/1; end /*i*/ /*process each number one at a time. */
if ord\=='' & ord<0 then call ser ord "(ner) can't be negative"
/* [↓] process the optional order. */
if ord\=='' & ord>w then call ser ord "(ner) can't be greater than" w
if N=='' then parse value 0 # # with bot top N /*define the default order range. */
say right(w 'numbers: ' numbers,64) /*sloppy way to do a header, ... */
else parse var N bot 1 top /*Not specified? Then use only 1 order*/
say right(copies('─',length(numbers)),64) /* and the header fence.*/
say right(# 'numbers:', 44) e /*display the header title and ··· */
if ord=='' then do; bot=0; top=w; end /*define default ners.*/
say left('', 44)copies('─', length(e)+2) else/* do; " bot=n; top=n; " " fence. end /*just a specific ner?*/
/* [↓] where da rubber meets da road. */
/*═════════════════════════════════════════where da rubber meets da road*/
do ordero=bot to top; do r=1 for w#; !.r=@.r; end /*r*/; $=
do j=1 for ordero; d=!.j; do k=j+1 to w#; parse value !.k !.k-d with /*orderd diff!.k; end /*k*/
parse value !.k !.k-d with d !.k
end /*k*/
end /*j*/
do i=ordero+1 to w#; $=$ !.i/*build1; list. end /*i*/
if $=='' then $=' [null]'
$=$ !.i/1 /*append it. */
say right(o, 7)th(o)'─order forward difference vector =' $
end /*i*/
if $=='' then $='[null]' end /*pretty nullo*/
exit /*stick a fork in it, we're all done. */
what=right(order,length(w))th(order)'-order' /*nice format*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
say what 'forward difference vector = ' strip($) /*display it.*/
th: procedure; x=abs(arg(1)); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4))</syntaxhighlight>
end /*o*/
'''output''' &nbsp; when using the default input:
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────SER subroutine──────────────────────*/
ser: say; say '*** error! ***'; say arg(1); say; exit 13
/*──────────────────────────────────TH subroutine───────────────────────*/
th: parse arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4))</lang>
{{out}} when the default input was used
<pre>
10 numbers: 90 47 58 29 22 32 55 5 55 73
──────────────────────────── ──────────────────────────────
0th-order forward difference vector = 90 47 58 29 22 32 55 5 55 73
1st-order forward difference vector = -43 11 -29 -7 10 23 -50 50 18
2nd-order forward difference vector = 54 -40 22 17 13 -73 100 -32
3rd-order forward difference vector = -94 62 -5 -4 -86 173 -132
4th-order forward difference vector = 156 -67 1 -82 259 -305
5th-order forward difference vector = -223 68 -83 341 -564
6th-order forward difference vector = 291 -151 424 -905
7th-order forward difference vector = -442 575 -1329
8th-order forward difference vector = 1017 -1904
9th-order forward difference vector = -2921
10th-order forward difference vector = [null]
</pre>
{{out}}'''output''' &nbsp; when the '''TCLTcl''''s input was used: &nbsp; <tt> 90.5 47 58 29 22 32 55 5 55 73.5 </tt>
<pre>
0th-order forward difference vector = 10 numbers: 90.5 47 58 29 22 32 55 5 55 73.5
──────────────────────────────────
1st-order forward difference vector = -43.5 11 -29 -7 10 23 -50 50 18.5
2nd 0th-order forward difference vector = 5490.5 -4047 58 29 22 1732 1355 -735 10055 -3173.5
3rd 1st-order forward difference vector = -9443.5 6211 -529 -47 -8610 17323 -13150 50 18.5
4th 2nd-order forward difference vector = 15654.5 -6740 22 17 113 -8273 259100 -30431.5
5th 3rd-order forward difference vector = -22394.5 6862 -5 -4 -8386 341173 -563131.5
6th 4th-order forward difference vector = 291156.5 -15167 1 -82 424259 -904304.5
7th 5th-order forward difference vector = -442223.5 57568 -83 341 -1328563.5
8th 6th-order forward difference vector = 1017291.5 -1903151 424 -904.5
9th 7th-order forward difference vector = -2921442.5 575 -1328.5
10th 8th-order forward difference vector = [null]1017.5 -1903.5
9th-order forward difference vector = -2921
10th-order forward difference vector = [null]
</pre>
 
===with error checking===
<syntaxhighlight lang="rexx">/*REXX program computes the forward difference of a list of numbers. */
numeric digits 100 /*ensure enough accuracy (decimal digs)*/
parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */
if e=='' then e=90 47 58 29 22 32 55 5 55 73 /*Not specified? Then use the default.*/
#=words(e) /*# is the number of elements in list.*/
/* [↓] verify list items are numeric. */
do i=1 for #; _=word(e, i) /*process each number one at a time. */
if \datatype(_, 'N') then call ser _ "isn't a valid number"; @.i=_/1
end /*i*/ /* [↑] removes superfluous stuff. */
/* [↓] process the optional order. */
if N=='' then parse value 0 # # with bot top N /*define the default order range. */
else parse var N bot 1 top /*Not specified? Then use only 1 order*/
if #==0 then call ser "no numbers were specified."
if N<0 then call ser N "(order) can't be negative."
if N># then call ser N "(order) can't be greater than" #
say right(# 'numbers:', 44) e /*display the header (title) and ··· */
say left('', 44)copies('─', length(e)+2) /*display the header fence. */
/* [↓] where da rubber meets da road. */
do o=bot to top; do r=1 for #; !.r=@.r; end /*r*/; $=
do j=1 for o; d=!.j; do k=j+1 to #; parse value !.k !.k-d with d !.k; end /*k*/
end /*j*/
do i=o+1 to #; $=$ !.i/1; end /*i*/
if $=='' then $=' [null]'
say right(o, 7)th(o)'─order forward difference vector =' $
end /*o*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error***'; say arg(1); say; exit 13
th: procedure; x=abs(arg(1)); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4))</syntaxhighlight>
'''output''' &nbsp; is the same as the REXX entry above.
 
===with output alignment===
<syntaxhighlight lang="rexx">/*REXX program computes the forward difference of a list of numbers. */
numeric digits 100 /*ensure enough accuracy (decimal digs)*/
parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */
if e=='' then e=90 47 58 29 22 32 55 5 55 73 /*Not specified? Then use the default.*/
#=words(e); w=5 /*# is the number of elements in list.*/
/* [↓] verify list items are numeric. */
do i=1 for #; _=word(e, i) /*process each number one at a time. */
if \datatype(_, 'N') then call ser _ "isn't a valid number"; @.i=_/1
w=max(w, length(@.i)) /*use the maximum length of an element.*/
end /*i*/ /* [↑] removes superfluous stuff. */
/* [↓] process the optional order. */
if N=='' then parse value 0 # # with bot top N /*define the default order range. */
else parse var N bot 1 top /*Not specified? Then use only 1 order*/
if #==0 then call ser "no numbers were specified."
if N<0 then call ser N "(order) can't be negative."
if N># then call ser N "(order) can't be greater than" #
_=; do k=1 for #; _=_ right(@.k, w); end /*k*/; _=substr(_, 2)
say right(# 'numbers:', 44) _ /*display the header title and ··· */
say left('', 44)copies('─', w*#+#) /* " " " fence. */
/* [↓] where da rubber meets da road. */
do o=bot to top; do r=1 for #; !.r=@.r; end /*r*/; $=
do j=1 for o; d=!.j; do k=j+1 to #; parse value !.k !.k-d with d !.k
w=max(w, length(!.k))
end /*k*/
end /*j*/
do i=o+1 to #; $=$ right(!.i/1, w); end /*i*/
if $=='' then $=' [null]'
say right(o, 7)th(o)'─order forward difference vector =' $
end /*o*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ser: say; say '***error***'; say arg(1); say; exit 13
th: procedure; x=abs(arg(1)); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4))</syntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
10 numbers: 90 47 58 29 22 32 55 5 55 73
────────────────────────────────────────────────────────────
0th─order forward difference vector = 90 47 58 29 22 32 55 5 55 73
1st─order forward difference vector = -43 11 -29 -7 10 23 -50 50 18
2nd─order forward difference vector = 54 -40 22 17 13 -73 100 -32
3rd─order forward difference vector = -94 62 -5 -4 -86 173 -132
4th─order forward difference vector = 156 -67 1 -82 259 -305
5th─order forward difference vector = -223 68 -83 341 -564
6th─order forward difference vector = 291 -151 424 -905
7th─order forward difference vector = -442 575 -1329
8th─order forward difference vector = 1017 -1904
9th─order forward difference vector = -2921
10th─order forward difference vector = [null]
</pre>
 
===Version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Forward differences
* 18.08.2012 Walter Pachl derived from PL/I
Line 1,767 ⟶ 2,922:
End
End
Return</langsyntaxhighlight>
{{out}} for Java's input
<pre>
Line 1,784 ⟶ 2,939:
n is too large: 11 > 10
</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Forward difference
 
s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
for p = 1 to 9
s = fwddiff(s)
showarray(s)
next
 
func fwddiff(s)
for j=1 to len(s)-1
s[j] = s[j+1]-s[j]
next
n = len(s)
del(s, n)
return s
 
func showarray(vect)
see "{"
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n] + ", "
next
svect = left(svect, len(svect) - 2)
see svect
see "}" + nl
</syntaxhighlight>
Output:
<pre>
{-43, 11, -29, -7, 10, 23, -50, 50, 18}
{54, -40, 22, 17, 13, -73, 100, -32}
{-94, 62, -5, -4, -86, 173, -132}
{156, -67, 1, -82, 259, -305}
{-223, 68, -83, 341, -564}
{291, -151, 424, -905}
{-442, 575, -1329}
{1017, -1904}
{-2921}
</pre>
 
=={{header|RPL}}==
===Iterative approach===
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
'''IF''' OVER SIZE OVER > '''THEN'''
'''WHILE''' DUP '''REPEAT'''
SWAP { } 2 3 PICK SIZE '''FOR''' j
OVER j GET + '''NEXT'''
LIST→ →ARRY
SWAP OVER SIZE { } + RDM -
SWAP 1 - '''END'''
DROP '''END'''
≫ ‘<span style="color:blue">DIFFN</span>’ STO
|
<span style="color:blue">DIFFN</span> ''( [array] order → [nth_difference] ) ''
if order < array size
while order > 0
initialize loop
to build { array[2]...array[n] }
convert list into array
pop last item of array and substract
order -= 1
clean stack
|}
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73] 1 <span style="color:blue">DIFFN</span>
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73] 3 <span style="color:blue">DIFFN</span>
{{out}}
<pre>
2: [-43, 11, -29, -7, 10, 23, -50, 50, 18]
1: [-94, 62, -5, -4, -86, 173, -132]
</pre>
===Direct approach===
We use here local variables and algebraic notation to increase code readability.
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
≪ → n
≪ '<span style="color:green">F</span>' STO
{ } 1 <span style="color:green">F</span> SIZE 1 - '''FOR''' j
-1 n ^ '<span style="color:green">F</span>' j GET *
1 n '''FOR''' k
'COMB(n,k)*(-1)^(n-k)*<span style="color:green">F</span>(j+k)' EVAL +
'''NEXT'''
+ '''NEXT'''
LIST→ →ARRY '<span style="color:green">F</span>' PURGE
≫ ≫ ‘<span style="color:blue">DIFFN</span>’ STO
|
<span style="color:blue">DIFFN</span> ''( [array] order → [nth_difference] ) ''
store array in global variable F
initialize output array building loop
put 1st term of sum (k=0) in stack // reverse Polish notation
loop
add terms for 0<k≤n // algebraic notation
add sum to list
convert list into array, clean memory
|}
Postfix fans can replace the following line
'COMB(n,k)*(-1)^(n-k)*<span style="color:green">F</span>(j+k)' EVAL + '''NEXT'''
by
n k COMB -1 n k - ^ * '<span style="color:green">F</span>' j k + GET * + '''NEXT'''
On HP-48G and newer models, first difference is directly returned by the <code>ΔLIST</code> instruction, so we can simplify the above code, provided that input is given as a list { } instead of an array [ ]:
≪ 1 SWAP '''START''' ΔLIST '''NEXT''' ≫ ‘<span style="color:blue">DIFFN</span>’ STO
 
 
=={{header|Ruby}}==
Line 1,792 ⟶ 3,061:
 
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">def dif(s)
s.each_cons(2).collect { |x, y| y - x }
end
Line 1,798 ⟶ 3,067:
def difn(s, n)
n.times.inject(s) { |s, | dif(s) }
end</langsyntaxhighlight>
 
{{out|Example usage}}
<langsyntaxhighlight lang="ruby">p dif([1, 23, 45, 678]) # => [22, 22, 633]
p difn([1, 23, 45, 678], 2) # => [0, 611]</langsyntaxhighlight>
 
=={{header|Rust}}==
 
<syntaxhighlight lang="rust">
fn forward_difference(input_seq: Vec<i32>, order: u32) -> Vec<i32> {
match order {
0 => input_seq,
1 => {
let input_seq_iter = input_seq.into_iter();
let clone_of_input_seq_iter = input_seq_iter.clone();
input_seq_iter.zip(clone_of_input_seq_iter.skip(1)).map(|(current, next)| next - current).collect()
},
_ => forward_difference(forward_difference(input_seq, order - 1), 1),
}
}
 
fn main() {
let mut sequence = vec![90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
loop {
println!("{:?}", sequence);
sequence = forward_difference(sequence, 1);
if sequence.is_empty() {
break;
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
[54, -40, 22, 17, 13, -73, 100, -32]
[-94, 62, -5, -4, -86, 173, -132]
[156, -67, 1, -82, 259, -305]
[-223, 68, -83, 341, -564]
[291, -151, 424, -905]
[-442, 575, -1329]
[1017, -1904]
[-2921]
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def fdiff(xs: List[Int]) = (xs.tail, xs).zipped.map(_ - _)
 
def fdiffn(i: Int, xs: List[Int]): List[Int] = if (i == 1) fdiff(xs) else fdiffn(i - 1, fdiff(xs))</langsyntaxhighlight>
 
{{out|Example}}
<langsyntaxhighlight lang="scala">val l=List(90,47,58,29,22,32,55,5,55,73)
(1 to 9)foreach(x=>println(fdiffn(x,l)))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,826 ⟶ 3,136:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (forward-diff lst)
(if (or (null? lst) (null? (cdr lst)))
'()
Line 1,836 ⟶ 3,146:
xs
(nth-forward-diff (- n 1)
(forward-diff xs))))</langsyntaxhighlight>
 
{{out}}
Line 1,845 ⟶ 3,155:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array integer: forwardDifference (in array integer: data) is func
Line 1,877 ⟶ 3,187:
data := forwardDifference(data);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,892 ⟶ 3,202:
-2921
</pre>
 
=={{header|SequenceL}}==
Solution that keeps track of intermediate values:
<syntaxhighlight lang="sequencel">
forwardDifference(x(1), n) := forwardDifferenceHelper(x, n, [x]);
 
forwardDifferenceHelper(x(1), n, result(2)) :=
let
difference := tail(x) - x[1 ... size(x) - 1];
in
result when n = 0 or size(x) = 1 else
forwardDifferenceHelper(difference, n - 1, result ++ [difference]);
</syntaxhighlight>
If no intermediate values are needed, the following is sufficient:
<syntaxhighlight lang="sequencel">
forwardDifference(x(1),n) :=
x when n = 0 or size(x) = 1 else
forwardDifference(tail(x) - x[1 ... size(x) - 1], n - 1);
</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func dif(arr) {
gather {
for i (0 ..^ arr.end) {
take(arr[i+1] - arr[i])
}
}
}
 
func difn(n, arr) {
{ arr = dif(arr) } * n
arr
}
 
say dif([1, 23, 45, 678]) # => [22, 22, 633]
say difn(2, [1, 23, 45, 678]) # => [0, 611]</syntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">s@(Sequence traits) forwardDifference
[
s allButFirst with: s allButLast collect: #- `er
Line 1,910 ⟶ 3,256:
[
(0 below: n) inject: s into: [| :seq :_ | seq forwardDifference]
].</langsyntaxhighlight>
 
{{out|Usage}}
<langsyntaxhighlight lang="slate">#data := ##(90 47 58 29 22 32 55 5 55 73).
data keysDo: [| :index | inform: (data forwardDifference: index) printString].</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">Array extend [
difference [
^self allButFirst with: self allButLast collect: [ :a :b | a - b ]
Line 1,931 ⟶ 3,277:
s := #(90 47 58 29 22 32 55 5 55 73)
1 to: s size - 1 do: [ :i |
(s nthOrderDifference: i) printNl ]</langsyntaxhighlight>
 
=={{header|SQL}}==
 
{{works with|SQLite|3.13.0}}
{{improve|SQL|This was not written by an experienced SQL programmer. If possible in standard SQL, convert to a form that doesn't require unrolled recursion to obtain the nth forward difference. Remove works-with if not appropriate.}}
 
<syntaxhighlight lang="sql">WITH RECURSIVE
{{works with|SQLite|3.6.22}}
T0 (N, ITEM, LIST, NEW_LIST) AS
 
(
<lang sql>create table list (n integer, v real);
SELECT 1,
insert into list values (0, 90);
NULL,
insert into list values (1, 47);
'90,47,58,29,22,32,55,5,55,73' || ',',
insert into list values (2, 58);
NULL
insert into list values (3, 29);
UNION ALL
insert into list values (4, 22);
SELECT CASE
insert into list values (5, 32);
WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''
insert into list values (6, 55);
THEN N + 1
insert into list values (7, 5);
ELSE N
insert into list values (8, 55);
END,
insert into list values (9, 73);
CASE
 
WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> ''
create view diff1 as select list.n, (select next.v from list as next where next.n = list.n + 1) - list.v as v from list;
THEN SUBSTR(LIST, 1, INSTR(LIST, ',') - 1)
create view diff2 as select list.n, (select next.v from diff1 as next where next.n = list.n + 1) - list.v as v from diff1 as list;
ELSE NULL
 
END,
select * from diff1;
0|-43.0 CASE
WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) = ''
1|11.0
THEN IFNULL(NEW_LIST || (SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '')
2|-29.0
ELSE SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST))
3|-7.0
4|10.0 END,
5|23.0 CASE
WHEN SUBSTR(LIST, INSTR(LIST, ',') + 1, LENGTH(LIST)) <> ''
6|-50.0
THEN IFNULL(NEW_LIST, '') || IFNULL((SUBSTR(LIST, 1, INSTR(LIST, ',') - 1) - ITEM) || ',', '')
7|50.0
ELSE NULL
8|18.0
9| END
FROM T0
select * from diff2;
WHERE INSTR(LIST, ',') > 0
0|54.0
)
1|-40.0
SELECT N,
2|22.0
TRIM(LIST, ',') LIST
3|17.0
FROM 4|13.0T0
WHERE NEW_LIST IS NULL
5|-73.0
AND 6|100.0LIST <> ''
ORDER BY N;</syntaxhighlight>
7|-32.0
8|
9|</lang>
 
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun forward_difference xs = ListPair.map op- (tl xs, xs)
 
fun nth_forward_difference n xs =
Line 1,985 ⟶ 3,329:
xs
else
nth_forward_difference (n-1) (forward_difference xs)</langsyntaxhighlight>
 
{{out}}
Line 1,992 ⟶ 3,336:
val it = [~2921] : int list
</pre>
 
=={{header|Stata}}==
It's possible to implement differences using row indices. For instance, first forward differences of a variable x can be defined by:
 
<syntaxhighlight lang="stata">gen y=x[_n+1]-x[_n]</syntaxhighlight>
 
However, it's much more natural to use [http://www.stata.com/help.cgi?tsvarlist time-series varlists]. In order to use them, it's necessary to first set a ''time'' variable, which may be simply an index variable.
 
<syntaxhighlight lang="stata">* First create a dataset
clear all
set obs 100
gen i=_n
tsset i
gen x=rnormal()
 
* Differences
display "Difference order?" _request(k)
gen y=D${k}F${k}.x</syntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="swift">func forwardsDifference<T: SignedNumeric>(of arr: [T]) -> [T] {
return zip(arr.dropFirst(), arr).map({ $0.0 - $0.1 })
}
 
func nthForwardsDifference<T: SignedNumeric>(of arr: [T], n: Int) -> [T] {
assert(n >= 0)
 
switch (arr, n) {
case ([], _):
return []
case let (arr, 0):
return arr
case let (arr, i):
return nthForwardsDifference(of: forwardsDifference(of: arr), n: i - 1)
}
}
 
for diff in (0...9).map({ nthForwardsDifference(of: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73], n: $0) }) {
print(diff)
}</syntaxhighlight>
 
{{out}}
 
<pre>[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
[-43, 11, -29, -7, 10, 23, -50, 50, 18]
[54, -40, 22, 17, 13, -73, 100, -32]
[-94, 62, -5, -4, -86, 173, -132]
[156, -67, 1, -82, 259, -305]
[-223, 68, -83, 341, -564]
[291, -151, 424, -905]
[-442, 575, -1329]
[1017, -1904]
[-2921]</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc do_fwd_diff {list} {
set previous [lindex $list 0]
set new [list]
Line 2,016 ⟶ 3,414:
for {set order 0} {$order <= 10} {incr order} {
puts [format "%d\t%s" $order [fwd_diff $a $order]]
}</langsyntaxhighlight>
{{out}}
<pre>0 90.5 47 58 29 22 32 55 5 55 73.5
Line 2,033 ⟶ 3,431:
This function doesn't need to be defined because it's in a library already,
but it could be defined like this:
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import flo
 
nth_diff "n" = rep"n" minus*typ</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">test_data = <90.,47.,58.,29.,22.,32.,55.,5.,55.,73.>
 
#show+
Line 2,047 ⟶ 3,445:
printf/*=*' %0.0f' <
nth_diff6 test_data,
nth_diff7 test_data></langsyntaxhighlight>
{{out}}
<pre> 291 -151 424 -905
Line 2,054 ⟶ 3,452:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2008+}}
<langsyntaxhighlight lang="vbnet">Module ForwardDifference
 
Sub Main()
Line 2,075 ⟶ 3,473:
End Function
 
End Module</langsyntaxhighlight>
{{out}}
<pre>
Line 2,088 ⟶ 3,486:
1017 -1904
-2921
</pre>
 
=={{header|Visual FoxPro}}==
<syntaxhighlight lang="vfp">
#DEFINE CTAB CHR(9)
LOCAL lcList As String, i As Integer, n As Integer
n = 10
LOCAL ARRAY aa[n]
CLEAR
lcList = "90,47,58,29,22,32,55,5,55,73"
FOR i = 1 TO n
aa[i] = VAL(GETWORDNUM(lcList, i, ","))
ENDFOR
ShowOutput("Original", @aa)
k = n - 1
FOR i = 1 TO n - 1
ForwardDiff(@aa)
ShowOutput("Difference " + TRANSFORM(i), @aa)
ENDFOR
 
PROCEDURE ForwardDiff(a)
LOCAL i As Integer, n As Integer
n = ALEN(a)
LOCAL ARRAY b[n-1]
FOR i = 1 TO n - 1
b[i] = a[i+1] - a[i]
ENDFOR
DIMENSION a[n-1]
ACOPY(b, a)
ENDPROC
 
PROCEDURE ShowOutput(lcLabel, zz)
LOCAL i As Integer, n As Integer, lcTxt As String
n = ALEN(zz)
lcTxt = lcLabel + ":" + CTAB
FOR i = 1 TO n
lcTxt = lcTxt + TRANSFORM(zz[i]) + CTAB
ENDFOR
lcTxt = LEFT(lcTxt, LEN(lcTxt) - 1)
? lcTxt
ENDPROC
</syntaxhighlight>
{{out}}
<pre>
Original: 90 47 58 29 22 32 55 5 55 73
Difference 1: -43 11 -29 -7 10 23 -50 50 18
Difference 2: 54 -40 22 17 13 -73 100 -32
Difference 3: -94 62 -5 -4 -86 173 -132
Difference 4: 156 -67 1 -82 259 -305
Difference 5: -223 68 -83 341 -564
Difference 6: 291 -151 424 -905
Difference 7: -442 575 -1329
Difference 8: 1017 -1904
Difference 9: -2921
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Fmt
 
var forwardDiff = Fn.new { |a, order|
if (order < 0) Fiber.abort("Order must be a non-negative integer.")
if (a.count == 0) return
Fmt.print(" 0: $5d", a)
if (a.count == 1) return
if (order == 0) return
for (o in 1..order) {
var b = List.filled(a.count-1, 0)
for (i in 0...b.count) b[i] = a[i+1] - a[i]
Fmt.print("$2d: $5d", o, b)
if (b.count == 1) return
a = b
}
}
 
forwardDiff.call([90, 47, 58, 29, 22, 32, 55, 5, 55, 73], 9)</syntaxhighlight>
 
{{out}}
<pre>
0: 90 47 58 29 22 32 55 5 55 73
1: -43 11 -29 -7 10 23 -50 50 18
2: 54 -40 22 17 13 -73 100 -32
3: -94 62 -5 -4 -86 173 -132
4: 156 -67 1 -82 259 -305
5: -223 68 -83 341 -564
6: 291 -151 424 -905
7: -442 575 -1329
8: 1017 -1904
9: -2921
</pre>
 
=={{header|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0">\Calculate forward differences
 
\Sets elements of B to the first order forward differences of A.
\A should have bounds 1 :: N, B should have bounds 1 :: N - 1.
procedure FirstOrderFDifference ( A, B, N );
integer A, B, N, I;
for I := 2 to N do B( I - 1 ) := A( I ) - A( I - 1 );
 
integer V ( 1 + 10 );
integer Diff( 1 + 9 );
integer VPos, Length, List, I, Order;
begin
\construct the initial values array
VPos := 1;
List:= [90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
for I := 0 to 10-1 do begin
V( VPos ) := List( I );
VPos := VPos + 1
end;
 
\calculate and show the differences
Format(8, 0); \set output format
Length := 10;
for Order := 1 to Length - 1 do begin
FirstOrderFDifference( V, Diff, Length );
Length := Length - 1;
IntOut(0, Order); Text(0, " : ");
for I := 1 to Length do RlOut(0, float(Diff( I ) ));
CrLf(0);
for I := 1 to Length do V( I ) := Diff( I )
end
end</syntaxhighlight>
{{out}}
<pre>
1 : -43 11 -29 -7 10 23 -50 50 18
2 : 54 -40 22 17 13 -73 100 -32
3 : -94 62 -5 -4 -86 173 -132
4 : 156 -67 1 -82 259 -305
5 : -223 68 -83 341 -564
6 : 291 -151 424 -905
7 : -442 575 -1329
8 : 1017 -1904
9 : -2921
</pre>
 
=={{header|zkl}}==
{{trans|Scheme}}
<langsyntaxhighlight lang="zkl">fcn forwardDiff(lst){
if(lst.len()<2)
return(T);
return(T(lst[1]-lst[0]).extend(forwardDiff(lst[1,*])))}
}
 
fcn nthForwardDiff(n,xs){
if(n==0)
return(xs);
return(nthForwardDiff(n-1,forwardDiff(xs)))} // tail recursion</lang>
}</syntaxhighlight>
<syntaxhighlight lang="zkl">nthForwardDiff(9,T(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)).println();</syntaxhighlight>
{{out}}
<pre>
nthForwardDiff(9,T(90, 47, 58, 29, 22, 32, 55, 5, 55, 73))
L(-2921)
</pre>
 
=={{header|ZX Spectrum Basic}}==
<syntaxhighlight lang="zxbasic">10 DATA 9,0,1,2,4,7,4,2,1,0
20 LET p=1
30 READ n: DIM b(n)
40 FOR i=1 TO n
50 READ b(i)
60 NEXT i
70 FOR j=1 TO p
80 FOR i=1 TO n-j
90 LET b(i)=b(i+1)-b(i)
100 NEXT i
110 NEXT j
120 FOR i=1 TO n-p
130 PRINT b(i);" ";
140 NEXT i</syntaxhighlight>
9,485

edits