Wolfram Research

Function Repository Resource:

DifferencesBy

Source Notebook

Apply a function to neighboring pairs in a list

Contributed by: Bob Sandheinrich

ResourceFunction["DifferencesBy"][list,f]

applies f to successive neighboring pairs of element in list.

ResourceFunction["DifferencesBy"][f]

represents an operator form of ResourceFunction["DifferencesBy"].

Details and Options

The result of ResourceFunction["DifferencesBy"][{e1,e2,e3,},f] is {f[e2,e1],f[e3,e2],}.
The output of ResourceFunction["DifferencesBy"] contains one fewer element than list.

Examples

Basic Examples

Find differences between images:

In[1]:=
images = RandomSample[Keys[ResourceData["MNIST"]], 10]
Out[1]=
In[2]:=
ResourceFunction["DifferencesBy"][images, ImageDifference]
Out[2]=

Find the elements of each sublist that are absent from the proceeding sublist:

In[3]:=
ResourceFunction[
 "DifferencesBy"][{{1, 2}, {1, 3}, {1, 2, 3, 4}}, Complement]
Out[3]=

Scope

Create an operator:

In[4]:=
bigger = ResourceFunction["DifferencesBy"][
  With[{max = Max[#2]}, Select[#1, # > max &]] &]
Out[4]=
In[5]:=
bigger[{{1, 5, 4}, {2, 6, 3, 8}, {11, 4, 2, 0}, {4, 5}, {3, 4, 5, 6}}]
Out[5]=

Applications

Find vocabulary differences:

In[6]:=
Short /@ ResourceFunction["DifferencesBy"][
  {ResourceData["Hamlet"], ResourceData["Shakespeare's Sonnets"], ResourceData["Friends, Romans, Countrymen"]},
  Complement[ToLowerCase@TextWords[#1], ToLowerCase@TextWords[#2]] &]
Out[6]=

Look at the growth of the string-based SubstitutionSystem:

In[7]:=
subsys = SubstitutionSystem[{"A" -> "AB", "B" -> "A"}, "A", 11]
Out[7]=
In[8]:=
ResourceFunction["DifferencesBy"][subsys, StringCount[#1, "B"] - StringCount[#2, "B"] &]
Out[8]=

Properties and Relations

DifferencesBy is a generalization of Differences:

In[9]:=
Differences[Prime /@ Range[10]]
Out[9]=

Using Subtract as f gives the same result:

In[10]:=
ResourceFunction["DifferencesBy"][Prime /@ Range[10], Subtract]
Out[10]=

The function passed to DifferencesBy does not need to be subtraction:

In[11]:=
ResourceFunction["DifferencesBy"][Range[10], f]
Out[11]=
In[12]:=
ResourceFunction["DifferencesBy"][Range[10], Times]
Out[12]=

Resource History

Related Resources