Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Interpret input and check that the resulting expression matches a specific pattern
ResourceFunction["ToExpressionMatched"][input,patt] interprets input as an expression only if the unevaluated form matches patt. | |
ResourceFunction["ToExpressionMatched"][input,patt,form] uses interpretation rules corresponding to the specified form. | |
ResourceFunction["ToExpressionMatched"][input,patt,form,h] wraps the head h around the expression produced before evaluating it. | |
ResourceFunction["ToExpressionMatched"][input,patt,Automatic,h] uses the default interpretation rules from ToExpression. |
Interpret a string, expecting an integer:
In[1]:= | ![]() |
Out[1]= | ![]() |
A failure is generated if the result does not match:
In[2]:= | ![]() |
Out[2]= | ![]() |
The pattern is checked before evaluation, so this fails because the head of the interpreted input is Plus:
In[3]:= | ![]() |
Out[3]= | ![]() |
Check that the head is Plus:
In[4]:= | ![]() |
Out[4]= | ![]() |
Instead, check that the input is a sum of integers:
In[5]:= | ![]() |
Out[5]= | ![]() |
If the input cannot be interpreted as a valid expression, ToExpressionMatched behaves similarly as ToExpression, but it generates a Failure object instead of $Failed:
In[6]:= | ![]() |
Out[6]= | ![]() |
Interpret boxes:
In[7]:= | ![]() |
Out[7]= | ![]() |
Wrap a head around the expression before returning it:
In[8]:= | ![]() |
Out[8]= | ![]() |
No head will be applied if a failure is generated:
In[9]:= | ![]() |
Out[9]= | ![]() |
In[10]:= | ![]() |
Out[10]= | ![]() |
Automatically determine the interpretation rules appropriate for the input:
In[11]:= | ![]() |
Out[11]= | ![]() |
In[12]:= | ![]() |
Out[12]= | ![]() |
This work is licensed under a Creative Commons Attribution 4.0 International License