1
$\begingroup$

I understand that

Clear[a,b,c]
MatchQ[a+b+c, Plus[__]]
True

Because a+b+c is in fact Plus[a,b,c], and the number of arguments in Plus is 3, which is bigger then 0. So it fits for two continuous underlines (__) in Plus.

But I can't understand the followings:

MatchQ[abc, Plus[__]]
True

MatchQ["abc", Plus[__]]
True

MatchQ[a b c, Plus[__]]
True

abc is a just symbol, a b c is Times[a,b,c] and "abc" is a just string. Why does MatchQ gives True for these inputs?

I've been using Mathematica for long time... The incomprehensible True makes me feel like I'm in a dream.

$\endgroup$
3
  • 2
    $\begingroup$ abc is Times[a,b,c] no, it is not. space is important. a b c is Times[a,b,c], but abc is just a symbol $\endgroup$
    – Nasser
    Commented Feb 20, 2023 at 3:08
  • 2
    $\begingroup$ abc is not Times[...] but a variable. Try: MatchQ["abc", Plus[__]] // Trace to see the evaluation sequence. $\endgroup$
    – Syed
    Commented Feb 20, 2023 at 3:09
  • $\begingroup$ @Nasser, I corrected the mistake in my question, but I still do not know yet. $\endgroup$
    – imida k
    Commented Feb 20, 2023 at 3:14

1 Answer 1

6
$\begingroup$

If a function doesn't have a Hold* attribute, its argument(s) will always be evaluated before going into the function. MatchQ is such a function, so Plus[__] evaluates first and becomes __. This can be checked with Trace:

MatchQ[abc, Plus[__]] // Trace

enter image description here

The standard way to stop the automatic calculation in this case is to use HoldPattern:

MatchQ[abc, HoldPattern@Plus[__]]
(* False *)

Alternatively:

MatchQ[abc, (h : Plus)[__]]
MatchQ[abc, __Plus]
$\endgroup$
3
  • $\begingroup$ Thank you! I'm quite weak in Hold, evaluation,... something very new at least for me. $\endgroup$
    – imida k
    Commented Feb 20, 2023 at 3:21
  • 3
    $\begingroup$ @imidak Indeed, evaluation control is advanced topic in Mathematica. Just keep the line "If a function doesn't have a Hold* attribute, its argument(s) will always be evaluated before going into the function" in mind, you'll gradually get used to it :) . $\endgroup$
    – xzczd
    Commented Feb 20, 2023 at 3:26
  • $\begingroup$ Thank you again! $\endgroup$
    – imida k
    Commented Feb 20, 2023 at 3:28

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