Skip to content

Condition

pat /; cond matches an expression if the expression matches pat, and if cond evaluates to True with all the named patterns substituted in.

Attributes[Condition] := {HoldAll, Protected}

Simple examples

In[1]:= MatchQ[5, Condition[_, True]]
Out[1]= True
In[2]:= MatchQ[5, Condition[_, False]]
Out[2]= False
In[3]:= MatchQ[5, Condition[y_, True]]
Out[3]= True
In[4]:= MatchQ[5, Condition[y_Real, True]]
Out[4]= False
In[5]:= MatchQ[5, Condition[y_Integer, True]]
Out[5]= True
In[6]:= MatchQ[5, Condition[y_, y == 0]]
Out[6]= False
In[7]:= MatchQ[5, Condition[y_, y == 5]]
Out[7]= True
In[8]:= ({3, 5, 2, 1}) //. ((Condition[{x___, y_, z_, k___}, Order[y, z] == -1] -> {x, z, y, k}))
Out[8]= {1, 2, 3, 5}
In[9]:= Replace[1, a_Integer :> Condition[myfn[a], (a) > (0)]]
Out[9]= myfn[1]
In[10]:= Replace[-1, a_Integer :> Condition[myfn[a], (a) > (0)]]
Out[10]= -1
In[11]:= Replace[foo[2, 3], foo[x_, y_] :> Condition[With[{a = x}, Condition[x^2, a == 2]], y == 3]]
Out[11]= 4
In[12]:= Replace[foo[3, 3], foo[x_, y_] :> Condition[With[{a = x}, Condition[x^2, a == 2]], y == 3]]
Out[12]= foo[3, 3]
In[13]:= Replace[foo[2, 4], foo[x_, y_] :> Condition[With[{a = x}, Condition[x^2, a == 2]], y == 3]]
Out[13]= foo[2, 4]
In[14]:= Replace[bar[2], bar[x_] :> With[{a = x}, Condition[x^2, a == 2]]]
Out[14]= 4
In[15]:= Replace[bar[3], bar[x_] :> With[{a = x}, Condition[x^2, a == 2]]]
Out[15]= bar[3]
In[16]:= Replace[foo[2, 3], foo[x_, y_] :> Condition[Module[{a = x}, Condition[x^2, a == 2]], y == 3]]
Out[16]= 4
In[17]:= Replace[foo[3, 3], foo[x_, y_] :> Condition[Module[{a = x}, Condition[x^2, a == 2]], y == 3]]
Out[17]= foo[3, 3]
In[18]:= Replace[foo[2, 4], foo[x_, y_] :> Condition[Module[{a = x}, Condition[x^2, a == 2]], y == 3]]
Out[18]= foo[2, 4]
In[19]:= Replace[bar[2], bar[x_] :> Module[{a = x}, Condition[x^2, a == 2]]]
Out[19]= 4
In[20]:= Replace[bar[3], bar[x_] :> Module[{a = x}, Condition[x^2, a == 2]]]
Out[20]= bar[3]
In[21]:= Replace[2, x_ :> Condition[Condition[Condition[x^2, x == 2], x == 2], x == 2]]
Out[21]= 4
In[22]:= Replace[3, x_ :> Condition[Condition[Condition[x^2, x == 2], x == 2], x == 2]]
Out[22]= 3