FirstCase

FirstCase[{e1,e2,},pattern]
gives the first to match pattern, or Missing["NotFound"] if none matching pattern is found.

FirstCase[{e1,},patternrhs]
gives the value of rhs corresponding to the first to match pattern.

FirstCase[expr,pattern,default]
gives default if no element matching pattern is found.

FirstCase[expr,pattern,default,levelspec]
finds only objects that appear on levels specified by levelspec.

FirstCase[pattern]
represents an operator form of FirstCase that can be applied to an expression.

Details and OptionsDetails and Options

  • The first argument to FirstCase need not have head List and can be an association.
  • FirstCase[expr,pattern:>rhs] evaluates rhs only when the pattern is found.
  • In FirstCase[{e1,e2,},pattern,default], default is only evaluated if none of the match.
  • FirstCase[pattern][expr] is equivalent to FirstCase[expr,pattern].
  • FirstCase uses standard level specifications:
  • nlevels through n
    Infinitylevels through Infinity
    {n}level n only
    {n1,n2}levels through
  • The default value for levelspec in FirstCase is .
  • A positive level n consists of all parts of expr specified by n indices.
  • A negative level -n consists of all parts of expr with depth n.
  • Level consists of numbers, symbols, and other objects that do not have subparts.
  • Level corresponds to the whole expression.
  • With the option setting Heads->True, FirstCase looks at heads of expressions and their parts.
  • FirstCase traverses the parts of expr in a depth-first order, with leaves visited before roots.

ExamplesExamplesopen allclose all

Basic Examples  (3)Basic Examples  (3)

Find the first element in a list matching an integer:

In[1]:=
Click for copyable input
Out[1]=

Find the first non-integer:

In[2]:=
Click for copyable input
Out[2]=

Return the from inside the first matched:

In[1]:=
Click for copyable input
Out[1]=

Pick an element from an Association:

In[1]:=
Click for copyable input
Out[1]=
Introduced in 2014
(10.0)