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"Truestop the evaluation and return the failure expression as soon as a message occurs
"RetryCount"0how many times to retry the evaluation if it fails
"RetryWait"0how long to wait before retrying
"Quiet"{}messages to ignore
"Message"Falseprint 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 (2) 

Check an evaluation to make sure its 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 (3) 

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 (2) 

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

Version History

  • 1.0.0 – 10 October 2018

License Information