Function Repository Resource:

MapIf

Source Notebook

Map a function for elements in a list when a test gives True

Contributed by: Taliesin Beynon

ResourceFunction["MapIf"][f,test,list]

applies f to only those values ei in list for which test[ei] gives True.

ResourceFunction["MapIf"][f,test]

is the operator form of MapIf.

Examples

Basic Examples (3) 

Apply a function only for values greater than five:

In[1]:=
ResourceFunction["MapIf"][f, # > 5 &, Range[10]]
Out[1]=

Use the operator form:

In[2]:=
ResourceFunction["MapIf"][f, # > 5 &][Range[10]]
Out[2]=

Apply a function only for arguments of certain head:

In[3]:=
ResourceFunction["MapIf"][ToExpression, Head[#] === String &, {3, a, "x^2", {}}]
Out[3]=

Get values for associations of length 2:

In[4]:=
ResourceFunction["MapIf"][Total[Values[#]] &, Length[#] == 2 &, <|a -> <|b -> 1, c -> 2|>, d -> <|e -> 4|>|>]
Out[4]=

Applications (1) 

Avoid error messages when there is no data available:

In[5]:=
ResourceFunction["MapIf"][PlanetaryMoonData[#, "Mass"] &, # =!= {} &, PlanetData[{Entity["Planet", "Mercury"], Entity["Planet", "Venus"], Entity["Planet", "Earth"], Entity["Planet", "Mars"]}, "Satellites",
   "EntityAssociation"]]
Out[5]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 10 January 2019

License Information