Function Repository Resource:

SetComplementMap

Source Notebook

Apply a function to elements at certain positions and another function to the rest of the elements

Contributed by: Faizon Zaman

ResourceFunction["SetComplementMap"][f1,f2,list,pos]

applies f1 to elements in list at positions pos and applies f2 to the rest of the elements.

Details

The fi are applied in the order given; f1 is applied to positions pos in the order they appear, and f2 is applied to the complement set in ascending order of position in list.

Examples

Basic Examples (2) 

Color numbers at particular positions red and color the rest blue:

In[1]:=
positions = Sort@RandomSample[Range[10], 5]
makeBlue = Style[#, Blue] &;
makeRed = Style[#, Red] &;
Out[1]=
In[2]:=
ResourceFunction["SetComplementMap"][makeRed, makeBlue, Range[10], positions]
Out[2]=

Rotate strings in a list and style them red while coloring the rest of the elements blue:

In[3]:=
list = {1, 2, "three", 4, "five", 6};
spositions = Position[list, _String]
rotateRed = Rotate[Style[#, Red], 180 Degree] &;
makeBlue = Style[#, Blue] &;
Out[4]=
In[5]:=
ResourceFunction[
 "SetComplementMap"][rotateRed, makeBlue, list, spositions]
Out[5]=

Scope (1) 

If only one function is given, the second function defaults to Identity:

In[6]:=
positions = Sort@RandomSample[Range[10], 5]
Out[6]=
In[7]:=
ResourceFunction["SetComplementMap"][makeBlue, Range[10], positions]
Out[7]=

Properties and Relations (2) 

If no functions are given, the list is returned:

In[8]:=
positions = Sort@RandomSample[Range[10], 5]
Out[8]=
In[9]:=
ResourceFunction["SetComplementMap"][Range[10], positions]
Out[9]=

The second function can change the list's shape:

In[10]:=
list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
positions = {1, 2, 5, 8, 9};
In[11]:=
ResourceFunction["SetComplementMap"][2 + # &, ReplaceAll[_?EvenQ :> Nothing], list, positions]
Out[11]=

Possible Issues (2) 

If a position is out of scope, a Failure is returned:

In[12]:=
positions = {1, 2, 6, 7, 9};
In[13]:=
positions //= ReplacePart[-1 -> 11]
Out[13]=
In[14]:=
ResourceFunction["SetComplementMap"][ReplaceAll[_?EvenQ -> Nothing], Range[10], positions]
Out[14]=

If the first function changes the list-length, then one or more end positions no longer exist, producing a Failure when one or the other function attempts to evaluate at those positions.

In[15]:=
positions = {1, 2, 3, 5, 7};
In[16]:=
ResourceFunction["SetComplementMap"][ReplaceAll[_?EvenQ -> Nothing], Range[10], positions]
Out[16]=

Changes of structure due to f2 do not have this issue:

In[17]:=
positions = Sort@RandomSample[Range[10], 5]
Out[17]=
In[18]:=
ResourceFunction["SetComplementMap"][2 # &, ReplaceAll[_?EvenQ -> Nothing], Range[10], positions]
Out[18]=

Publisher

Faizon Zaman

Requirements

Wolfram Language 12.3 (May 2021) or above

Version History

  • 1.1.0 – 27 November 2023
  • 1.0.0 – 19 July 2022

Related Resources

License Information