Wolfram Computation Meets Knowledge

SelectFirstBy

Contributed by: Taliesin Beynon (Wolfram Research)

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

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

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

Examples

Basic Examples

First factorial value greater than 1000:

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

If there are not elements satisfying criteria gives $Failed:

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

Applications

First element that satisfy an approximation according to some criteria:

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

First word consisting of 20 letters:

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

First element with a melting point greater than 1000 degrees:

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

Properties and Relations

SelectFirst uses a slightly different syntax:

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

Resource History