Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Evaluate expressions in turn until a given form is returned
ResourceFunction["FirstMatchingValue"][{expr1,expr2,…},pattern] evaluates expri in turn, returning the first result that matches pattern. | |
ResourceFunction["FirstMatchingValue"][{expr1,expr2,…},pattern→rhs] gives the value of rhs corresponding to the first value to match pattern. | |
ResourceFunction["FirstMatchingValue"][{expr1,expr2,…},pattern,default] gives default if no value matching pattern is found. | |
ResourceFunction["FirstMatchingValue"][expr,pattern,default, levelspec] finds only objects that appear on levels specified by levelspec. |
Find the first integer in a list without evaluating the following elements:
In[1]:= |
Out[1]= |
Expressions with side effects are evaluated once to check the returned value:
In[2]:= |
Out[2]= |
If no match is found, Missing["NotFound"] is returned:
In[3]:= |
Out[3]= |
The third argument can be used to specify the backup expression that should be evaluated if no match is found. This expression is only evaluated if necessary:
In[4]:= |
Out[4]= |
In[5]:= |
Out[5]= |
FirstMatchingValue supports replacement rules on the matching element:
In[6]:= |
Out[6]= |
Condition (/;) can be used to check additional constraints on the obtained value:
In[7]:= |
Out[7]= |
FirstMatchingValue supports standard level specifications:
In[8]:= |
Out[8]= |
When given an explicit list of elements, FirstMatchingValue returns the same element as FirstCase:
In[9]:= |
Out[9]= |
In[10]:= |
Out[10]= |
Unlike FirstCase, FirstMatchingValue does not evaluate any more expressions after a match has been found:
In[11]:= |
Out[11]= |
In[12]:= |
Out[12]= |
If you have a value that is expensive to compute and therefore worth storing for later use, FirstMatchingValue can be used to check various locations where the result could be stored and return the first successful lookup. The second evaluation of the following code will be much faster than the first:
In[13]:= |
Out[14]= |
This work is licensed under a Creative Commons Attribution 4.0 International License