Quantcast
Channel: Pattern matching and HoldForm - Mathematica Stack Exchange
Viewing all articles
Browse latest Browse all 2

Answer by Alexey Popkov for Pattern matching and HoldForm

$
0
0

As Leonid explained in the comment, HoldForm is not transparent for the pattern matcher as opposed to HoldPattern:

MatchQ[#, HoldForm[_]] & /@ {a, HoldForm[a]}MatchQ[#, HoldPattern[_]] & /@ {a, HoldForm[a]}
{False, True}{True, True}

From the above you see that an expression will match the pattern HoldForm[_] only if its Head is HoldForm. HoldPattern is specially designed to be transparent for the pattern matcher, and so HoldPattern[_] is equivalent to _ for the pattern matcher.

Condition (/;) is interpreted as a part of rule only if it is placed on level 1 inside it:

FullForm[lhs :> rhs /; test]    

RuleDelayed[lhs, Condition[rhs, test]]

{1, 2} /. x_Integer :> f[x] /; OddQ[x]   

{f[1], 2}

Mathematicaconverts such structures to undocumented RuleCondition for the purposes of pattern matching:

Trace[1 /. x_ :> f[x] /; OddQ[x]] (*=>  {{x_:>x/;test,x_:>x/;test},1/. x_:>x/;test,{RuleCondition[$ConditionHold[$ConditionHold[1]],test],Fail},1} *)

If one wraps Condition with arbitrary head it is no more a part of the rule:

{1, 2} /. x_Integer :> f[x /; OddQ[x]]    

{f[1 /; OddQ[1]], f[2 /; OddQ[2]]}

The role of such head may serve Identity as Leonid suggests:

{1, 2} /. x_Integer :> Identity[x /; OddQ[x]]    

{1 /; OddQ[1], 2 /; OddQ[2]}

HoldPattern is also suitable but it is not necessary in your case.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>