Forward difference: Difference between revisions

m
(→‎{{header|Python}}: Added a Python 3 draft.)
m (→‎{{header|Wren}}: Minor tidy)
 
(21 intermediate revisions by 14 users not shown)
Line 50:
{{trans|Python}}
 
<langsyntaxhighlight 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
Line 57:
 
L(i) 10
print(difn(s, i))</langsyntaxhighlight>
 
{{out}}
Line 74:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.containers.Vectors;
Line 123:
Print(Diff(A, 10));
print(Diff(A, 0));
end Forward_Difference;</langsyntaxhighlight>
{{out}}
<pre>
Line 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 158:
printf((list fmt,s,$";"l$))
OD
)</langsyntaxhighlight>
{{out}}
<pre>
Line 174:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% calculate forward differences %
 
Line 204:
for i := 1 until length do v( i ) := diff( i )
end for_order
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 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 229:
2 fd list
54 ¯40 22 17 13 ¯73 100 ¯32</langsyntaxhighlight>
 
=={{header|AppleScript}}==
{{Trans|JavaScript}}
 
<langsyntaxhighlight AppleScriptlang="applescript">-- forwardDifference :: Num a => [a] -> [a]
on forwardDifference(xs)
zipWith(my subtract, xs, rest of xs)
Line 453:
return lst
end tell
end zipWith</langsyntaxhighlight>
{{Out}}
<pre>0 -> [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]
Line 465:
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 484 ⟶ 507:
}
Return list
}</langsyntaxhighlight>
 
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
if (p<1) {p = 1};
Line 507 ⟶ 530:
{
print diff($0, p);
}</langsyntaxhighlight>
 
Using Pascal's triangle:
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
BEGIN {
if (p<1) {p = 1};
Line 537 ⟶ 560:
{
print diff($0, p);
}</langsyntaxhighlight>
 
{{out}}
Line 561 ⟶ 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 590 ⟶ 613:
a$ += STR$(a(i%)) + ", "
NEXT
= LEFT$(LEFT$(a$))</langsyntaxhighlight>
{{out}}
<pre>
Line 598 ⟶ 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 638 ⟶ 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 675 ⟶ 708:
printf("\n");
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 705 ⟶ 738:
} while ((sequence = ForwardDifference(sequence)).Any());
}
}</langsyntaxhighlight>
{{out}}
<pre>90, 47, 58, 29, 22, 32, 55, 5, 55, 73
Line 724 ⟶ 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 834 ⟶ 867:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 848 ⟶ 881:
 
===Using Standard Template Library===
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <numeric>
Line 865 ⟶ 898:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 880 ⟶ 913:
Usually one will not want the intermediate results,
in which case the following is sufficient:
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <numeric>
Line 894 ⟶ 927:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 901 ⟶ 934:
 
===Using Pascal's Triangle===
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <algorithm>
Line 916 ⟶ 949:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 923 ⟶ 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 939 ⟶ 972:
for n in [0..arr.length]
console.log n, forward_difference arr, n
</syntaxhighlight>
</lang>
{{out}}
<pre>> coffee forward_difference.coffee
Line 954 ⟶ 987:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun forward-difference (list)
(mapcar #'- (rest list) list))
 
Line 960 ⟶ 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 982 ⟶ 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 997 ⟶ 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 1,009 ⟶ 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 1,024 ⟶ 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 1,037 ⟶ 1,070:
a[n - 1][0 .. $ - 1])[0 .. $] }(D)
.take(D.length));
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">List forwardDifference(List _list) {
for (int i = _list.length - 1; i > 0; i--) {
_list[i] = _list[i] - _list[i - 1];
Line 1,056 ⟶ 1,089:
print(_list);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,072 ⟶ 1,105:
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 1,106 ⟶ 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 .
<langsyntaxhighlight lang="lisp">
(define (Δ-1 list)
(for/list ([x (cdr list)] [y list]) (- x y)))
Line 1,118 ⟶ 1,153:
((Δ-n 9) '(90 47 58 29 22 32 55 5 55 73))
→ (-2921)
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight Elixirlang="elixir">defmodule Diff do
def forward(list,i\\1) do
forward(list,[],i)
Line 1,135 ⟶ 1,170:
Enum.each(1..9, fn i ->
Diff.forward([90, 47, 58, 29, 22, 32, 55, 5, 55, 73],i)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,151 ⟶ 1,186:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(forward_difference).
-export([difference/1, difference/2]).
 
Line 1,168 ⟶ 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 1,188 ⟶ 1,223:
=={{header|F_Sharp|F#}}==
Straightforward recursive solution
<langsyntaxhighlight 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
Line 1,196 ⟶ 1,231:
|> 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</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: kernel math math.vectors sequences ;
IN: rosetacode
 
Line 1,208 ⟶ 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 1,227 ⟶ 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 1,250 ⟶ 1,285:
WRITE (*,*) b(1:arraysize-n)
END SUBROUTINE Fdiff
END MODULE DIFFERENCE</langsyntaxhighlight>
<langsyntaxhighlight lang="fortran">PROGRAM TEST
 
USE DIFFERENCE
Line 1,264 ⟶ 1,299:
END DO
 
END PROGRAM TEST</langsyntaxhighlight>
{{out}}
<pre>
Line 1,277 ⟶ 1,312:
-2921
</pre>
 
=={{Header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">function forward_difference( a() as uinteger ) as uinteger ptr
dim as uinteger ptr b = allocate( sizeof(uinteger) * (ubound(a)-1) )
for i as uinteger = 0 to ubound(a)-1
*(b+i) = a(i+1)-a(i)
next i
return b
end function
 
dim as uinteger a(0 to 15) = {2, 3, 5, 7, 11, 13, 17, 19,_
23, 29, 31, 37, 41, 43, 47, 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 1,296 ⟶ 1,351:
}
return a[:len(a)-ord]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,305 ⟶ 1,360:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">forwardDifference :: Num a => [a] -> [a]
forwardDifference = tail >>= zipWith (-)
 
Line 1,314 ⟶ 1,369:
main =
mapM_ print $
take 10 (iterate forwardDifference [90, 47, 58, 29, 22, 32, 55, 5, 55, 73])</langsyntaxhighlight>
{{Out}}
<pre>[90,47,58,29,22,32,55,5,55,73]
Line 1,328 ⟶ 1,383:
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n=10, list(n)
 
list = ( 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 )
Line 1,339 ⟶ 1,394:
ENDDO
 
END</langsyntaxhighlight>
{{out}}
<pre>0 90 47 58 29 22 32 55 5 55 73
Line 1,353 ⟶ 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 1,369 ⟶ 1,424:
every writes(!L," ")
write()
end</langsyntaxhighlight>
 
{{out|A sample run}}
Line 1,389 ⟶ 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 1,396 ⟶ 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:
<langsyntaxhighlight lang="j"> list=: 90 47 58 29 22 32 55 5 55 73 NB. Some numbers
 
1 fd list
Line 1,414 ⟶ 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,433 ⟶ 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,463 ⟶ 1,518:
return a;
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,478 ⟶ 1,533:
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,634 ⟶ 1,689:
// MAIN ---
return main();
})();</langsyntaxhighlight>
 
{{Out}}
Line 1,650 ⟶ 1,705:
=={{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,657 ⟶ 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,675 ⟶ 1,730:
[-2921]
[]
[]</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 1,681 ⟶ 1,736:
Using the built-in <code>diff</code> function, which returns the 1st forward difference:
 
<langsyntaxhighlight 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))</langsyntaxhighlight>
 
{{out}}
Line 1,699 ⟶ 1,754:
 
=={{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,716 ⟶ 1,771:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun forwardDifference(ia: IntArray, order: Int): IntArray {
Line 1,751 ⟶ 1,806:
printArray(fd)
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,769 ⟶ 1,824:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def fdiff
{lambda {:l}
Line 1,797 ⟶ 1,852:
[1017,-1904]
[-2921]
</syntaxhighlight>
</lang>
 
=={{header|Lasso}}==
<langsyntaxhighlight lang="lasso">#!/usr/bin/lasso9
define forwardDiff(values, order::integer=1) => {
Line 1,815 ⟶ 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,829 ⟶ 1,884:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to fwd.diff :l
if empty? :l [output []]
if empty? bf :l [output []]
Line 1,840 ⟶ 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|M2000 Interpreter}}==
Function Diff(a()) get an array by value (a shallow copy)
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Form 80, 40
Module Forward_difference {
Line 1,873 ⟶ 1,928:
Forward_difference
 
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,890 ⟶ 1,945:
=={{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,903 ⟶ 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,913 ⟶ 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,949 ⟶ 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,982 ⟶ 2,037:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class Test {
Line 2,019 ⟶ 2,074:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let rec forward_difference = function
a :: (b :: _ as xs) ->
b - a :: forward_difference xs
Line 2,033 ⟶ 2,088:
xs
else
nth_forward_difference (pred n) (forward_difference xs)</langsyntaxhighlight>
 
{{out}}
Line 2,043 ⟶ 2,098:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: forwardDiff(l) l right(l size 1 -) l zipWith(#-) ;
: forwardDiffN(n, l) l #[ forwardDiff dup println ] times(n) ;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,061 ⟶ 2,116:
 
=={{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 2,089 ⟶ 2,144:
begin
fowardDifference(a);
end.</langsyntaxhighlight>
{{out}}
<pre>:> ./ForwardDifference
Line 2,104 ⟶ 2,159:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub dif {
my @s = @_;
map { $s[$_+1] - $s[$_] } 0 .. $#s-1
Line 2,110 ⟶ 2,165:
 
@a = qw<90 47 58 29 22 32 55 5 55 73>;
while (@a) { printf('%6d', $_) for @a = dif @a; print "\n" }</langsyntaxhighlight>
{{out}}
<pre> -43 11 -29 -7 10 23 -50 50 18
Line 2,123 ⟶ 2,178:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function fwd_diff_n(sequence s, integer order)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
if order>=length(s) then ?9/0 end if
<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>
for i=1 to order do
<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>
for j=1 to length(s)-1 do
<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>
s[j] = s[j+1]-s[j]
<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>
end for
<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>
s = s[1..-2]
<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>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return s
<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>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
constant s = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
for i=1 to 9 do
?fwd_diff_n(s,i)
<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>
end for</lang>
<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>
Line 2,153 ⟶ 2,212:
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php"><?php
 
function forwardDiff($anArray, $times = 1) {
Line 2,195 ⟶ 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 2,216 ⟶ 2,321:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Forward differences. */ /* 23 April 2010 */
differences: procedure options (main);
Line 2,238 ⟶ 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 2,260 ⟶ 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 2,285 ⟶ 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 2,342 ⟶ 2,511:
EndIf
 
</syntaxhighlight>
</lang>
{{out}}
<pre>1 [43,-11,29,7,-10,-23,50,-50,-18]
Line 2,357 ⟶ 2,526:
=={{header|Python}}==
===Python 2===
<langsyntaxhighlight 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 2,380 ⟶ 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}}
<langsyntaxhighlight lang="python">'''Forward difference'''
 
 
Line 2,477 ⟶ 2,646:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>9th order forward difference of:
Line 2,495 ⟶ 2,664:
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 2,517 ⟶ 2,716:
 
print(forwarddif(v, 9))
print(fdiff(v, 9))</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 2,533 ⟶ 2,732:
(nth-forward-difference 9 '(90 47 58 29 22 32 55 5 55 73))
;; -> '(-2921)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,541 ⟶ 2,740:
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" perl6line>sub dif(@array [$, *@tail]) { @tail Z- @array }
sub difn($array, $n) { ($array, &dif ... *)[$n] }</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,549 ⟶ 2,748:
 
This version allows a specification of the list of numbers and/or which &nbsp; ''order'' &nbsp; to process.
<langsyntaxhighlight 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 */
Line 2,571 ⟶ 2,770:
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
th: procedure; x=abs(arg(1)); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4))</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,606 ⟶ 2,805:
 
===with error checking===
<langsyntaxhighlight 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 */
Line 2,634 ⟶ 2,833:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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))</langsyntaxhighlight>
'''output''' &nbsp; is the same as the REXX entry above.
 
===with output alignment===
<langsyntaxhighlight 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 */
Line 2,670 ⟶ 2,869:
/*──────────────────────────────────────────────────────────────────────────────────────*/
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))</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,689 ⟶ 2,888:
 
===Version 2===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Forward differences
* 18.08.2012 Walter Pachl derived from PL/I
Line 2,723 ⟶ 2,922:
End
End
Return</langsyntaxhighlight>
{{out}} for Java's input
<pre>
Line 2,742 ⟶ 2,941:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Forward difference
 
Line 2,768 ⟶ 2,967:
see svect
see "}" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,781 ⟶ 2,980:
{-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 2,789 ⟶ 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 2,795 ⟶ 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 2,823 ⟶ 3,136:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (forward-diff lst)
(if (or (null? lst) (null? (cdr lst)))
'()
Line 2,833 ⟶ 3,146:
xs
(nth-forward-diff (- n 1)
(forward-diff xs))))</langsyntaxhighlight>
 
{{out}}
Line 2,842 ⟶ 3,155:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array integer: forwardDifference (in array integer: data) is func
Line 2,874 ⟶ 3,187:
data := forwardDifference(data);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,892 ⟶ 3,205:
=={{header|SequenceL}}==
Solution that keeps track of intermediate values:
<syntaxhighlight lang="sequencel">
<lang sequenceL>
forwardDifference(x(1), n) := forwardDifferenceHelper(x, n, [x]);
 
Line 2,901 ⟶ 3,214:
result when n = 0 or size(x) = 1 else
forwardDifferenceHelper(difference, n - 1, result ++ [difference]);
</syntaxhighlight>
</lang>
If no intermediate values are needed, the following is sufficient:
<syntaxhighlight lang="sequencel">
<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>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func dif(arr) {
gather {
for i (0 ..^ arr.end) {
Line 2,924 ⟶ 3,237:
 
say dif([1, 23, 45, 678]) # => [22, 22, 633]
say difn(2, [1, 23, 45, 678]) # => [0, 611]</langsyntaxhighlight>
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">s@(Sequence traits) forwardDifference
[
s allButFirst with: s allButLast collect: #- `er
Line 2,943 ⟶ 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 2,964 ⟶ 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}}==
Line 2,970 ⟶ 3,283:
{{works with|SQLite|3.13.0}}
 
<langsyntaxhighlight lang="sql">WITH RECURSIVE
T0 (N, ITEM, LIST, NEW_LIST) AS
(
Line 3,006 ⟶ 3,319:
WHERE NEW_LIST IS NULL
AND LIST <> ''
ORDER BY N;</langsyntaxhighlight>
 
=={{header|Standard ML}}==
 
<langsyntaxhighlight lang="sml">fun forward_difference xs = ListPair.map op- (tl xs, xs)
 
fun nth_forward_difference n xs =
Line 3,016 ⟶ 3,329:
xs
else
nth_forward_difference (n-1) (forward_difference xs)</langsyntaxhighlight>
 
{{out}}
Line 3,027 ⟶ 3,340:
It's possible to implement differences using row indices. For instance, first forward differences of a variable x can be defined by:
 
<langsyntaxhighlight lang="stata">gen y=x[_n+1]-x[_n]</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="stata">* First create a dataset
clear all
set obs 100
Line 3,040 ⟶ 3,353:
* Differences
display "Difference order?" _request(k)
gen y=D${k}F${k}.x</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">func forwardsDifference<T: SignedNumeric>(of arr: [T]) -> [T] {
return zip(arr.dropFirst(), arr).map({ $0.0 - $0.1 })
}
Line 3,063 ⟶ 3,376:
for diff in (0...9).map({ nthForwardsDifference(of: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73], n: $0) }) {
print(diff)
}</langsyntaxhighlight>
 
{{out}}
Line 3,079 ⟶ 3,392:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc do_fwd_diff {list} {
set previous [lindex $list 0]
set new [list]
Line 3,101 ⟶ 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 3,118 ⟶ 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 3,132 ⟶ 3,445:
printf/*=*' %0.0f' <
nth_diff6 test_data,
nth_diff7 test_data></langsyntaxhighlight>
{{out}}
<pre> 291 -151 424 -905
Line 3,139 ⟶ 3,452:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2008+}}
<langsyntaxhighlight lang="vbnet">Module ForwardDifference
 
Sub Main()
Line 3,160 ⟶ 3,473:
End Function
 
End Module</langsyntaxhighlight>
{{out}}
<pre>
Line 3,176 ⟶ 3,489:
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
#DEFINE CTAB CHR(9)
LOCAL lcList As String, i As Integer, n As Integer
Line 3,214 ⟶ 3,527:
? lcTxt
ENDPROC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,227 ⟶ 3,540:
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);
Line 3,240 ⟶ 3,635:
return(xs);
return(nthForwardDiff(n-1,forwardDiff(xs))) // tail recursion
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">nthForwardDiff(9,T(90, 47, 58, 29, 22, 32, 55, 5, 55, 73)).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 3,248 ⟶ 3,643:
 
=={{header|ZX Spectrum Basic}}==
<langsyntaxhighlight lang="zxbasic">10 DATA 9,0,1,2,4,7,4,2,1,0
20 LET p=1
30 READ n: DIM b(n)
Line 3,261 ⟶ 3,656:
120 FOR i=1 TO n-p
130 PRINT b(i);" ";
140 NEXT i</langsyntaxhighlight>
9,476

edits