Consider defining a pattern rule, such as


As far as I understand Mathematica syntax, this rule means

whenever myFun appears with a single argument, replace the whole thing by the argument

Now, after the above definition, if we evaluate



we see that even though the pattern x__ clearly symbolizes more than one argument, the single argument rule still gets executed!

Is this intended behavior? Maybe my syntax use is improper? How should I specify a single argument pattern rule which does not register with more-than-one argument patterns?

  • $\begingroup$ @kglr If I try to define myFun[x_] = x without the execution delay, I get the same behavior though... $\endgroup$ – Kagaratsch Mar 16 '19 at 20:21
  • 1
    $\begingroup$ In the second case Set has the attribute HoldFirst resulting in the same behavior. $\endgroup$ – kglr Mar 16 '19 at 20:22

The pattern x__ is a Pattern object:

x__ //FullForm


While the pattern object represents multiple arguments in a Rule or a function definition, it is a single object. Hence, your definition applies.

Why are you applying a function to a Pattern object, this is an unusual thing to do. Pattern objects usually appear inside of function definitions (Set or SetDelayed) or inside of rules (Rule or RuleDelayed).

  • $\begingroup$ My trouble is that after the myFun[x_]:=x definition, if I try to use /.myFun[x__]->... type of substitutions, the substitution is applied to x__ instead of myFun[x__] which is mildly inconvenient. My workaround is to use /.myFun[x_,y__]->... instead. $\endgroup$ – Kagaratsch Mar 16 '19 at 21:14
  • 2
    $\begingroup$ @Kagaratsch Rule doesn't have any Hold attributes, so myFun evaluates. Typically, one works around this by using HoldPattern, e.g., /. HoldPattern[myFun[x__]] -> .... $\endgroup$ – Carl Woll Mar 16 '19 at 21:16
  • $\begingroup$ I see, very useful, thank you! $\endgroup$ – Kagaratsch Mar 16 '19 at 21:18
  • $\begingroup$ Is there a way to make Rule hold patterns by default? I tried Unprotect[Rule]; SetAttributes[Rule, HoldAll]; Protect[Rule]; and it seems to work that way, but I get some weird error messages along the way. $\endgroup$ – Kagaratsch Mar 16 '19 at 21:33
  • 2
    $\begingroup$ @Kagaratsch Changing Rule in this way is dangerous and not recommended. It will probably break some Mathematica functionality. $\endgroup$ – Carl Woll Mar 16 '19 at 22:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.