Function Repository Resource:

SelectFirstBy

Source Notebook

Apply a function to a list and select the first that satisfies a test

Contributed by: Taliesin Beynon

ResourceFunction["SelectFirstBy"][test,f,{e1,e2,}]

computes f[ei] until test gives True, or returns $Failed if none do.

Examples

Basic Examples (2) 

The first factorial value greater than 1,000:

In[1]:=
ResourceFunction["SelectFirstBy"][# > 1000 &, Factorial, Range[10]]
Out[1]=

If there are no elements satisfying a criterion, SelectFirstBy gives $Failed:

In[2]:=
ResourceFunction["SelectFirstBy"][# > 1 &, Sin, Range[0, \[Pi]/2, \[Pi]/10]]
Out[2]=

Applications (3) 

The first element that satisfies an approximation according to some criteria:

In[3]:=
ResourceFunction["SelectFirstBy"][# < 1/1000. &, # - Sin[#] &, 1/Range[1., 15.]]
Out[3]=

The first word consisting of 20 letters:

In[4]:=
ResourceFunction["SelectFirstBy"][Length[#] == 20 &, Characters, WordList[]]
Out[4]=

The first element with a melting point greater than 1,000 degrees:

In[5]:=
ResourceFunction["SelectFirstBy"][QuantityMagnitude[#] > 1000 &, ElementData[#, "MeltingPoint"] &, Range[118]]
Out[5]=

Properties and Relations (1) 

SelectFirst uses a slightly different syntax:

In[6]:=
SelectFirst[Table[ElementData[z, "MeltingPoint"], {z, 118}], QuantityMagnitude[#] > 1000 &]
Out[6]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 29 November 2018

License Information