Wolfram Research

Function Repository Resource:

CheckMatch

Source Notebook

Verify that an evaluation output matches a given pattern and produces no errors

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["CheckMatch"][eval,patt,fail]

returns the output of eval if it matches patt and generates no messages and fail otherwise.

ResourceFunction["CheckMatch"][eval,patt]

uses $Failed as the failure expression.

Details and Options

The following options can be given:
"FailOnMessage" True stop the evaluation and return the failure expression as soon as a message occurs
"RetryCount" 0 how many times to retry the evaluation if it fails
"RetryWait" 0 how long to wait before retrying
"Quiet" { } messages to ignore
"Message" False print a message if pattern does not match
If an evaluation matches the given pattern, its output is returned. Otherwise, a supplied failure expression is returned.

Examples

Basic Examples

Check an evaluation to make sure it’s output matches a pattern:

In[1]:=
ResourceFunction["CheckMatch"][RandomReal[], _Real]
Out[1]=
In[2]:=
ResourceFunction["CheckMatch"][RandomReal[], _Integer]
Out[2]=

Give an expression to return on failure:

In[3]:=
ResourceFunction["CheckMatch"][RandomReal[], _Real, Print["failed!"]]
Out[3]=
In[4]:=
ResourceFunction["CheckMatch"][RandomReal[], _Integer, Print["failed!"]]

Scope

The output is returned if no messages are generated and it matches the supplied pattern:

In[5]:=
ResourceFunction["CheckMatch"][1 + 1, _Integer, $Failed]
Out[5]=

The third argument is returned if the output does not match:

In[6]:=
ResourceFunction["CheckMatch"][1 + 1.0, _Integer, $Failed]
Out[6]=

If any message occurs during the evaluation, the third argument is returned:

In[7]:=
ResourceFunction["CheckMatch"][First[{}]; 1 + 1, _Integer, $Failed]
Out[7]=

Options

Retry an evaluation if it fails:

In[8]:=
n = -1;
ResourceFunction["CheckMatch"][n++, _?Positive, $Failed, "RetryCount" -> 3]
Out[9]=

Wait before attempting retries:

In[10]:=
t0 = AbsoluteTime[];
ResourceFunction["CheckMatch"][Round[AbsoluteTime[] - t0], t_ /; t >= 2, $Failed, "RetryCount" -> 3, "RetryWait" -> 1]
Out[11]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information