6
$\begingroup$

This is probably very elementary but I have not used the following and I cannot find anything online, and I was unable to find something here.

Can someone explain to me the differences amongst

f[x_]:=, f[x__]:=, f[x___]:=

and maybe give some practical examples so I can see the differences?

$\endgroup$
6
  • 6
    $\begingroup$ Consider g1[x_]:= {x}, g2[x__]:= {x}, and g3[x___]:={x} and compare g1[], g1[5] and g1[5,6] (similarly for g2 and g3). $\endgroup$
    – kglr
    Sep 24 '19 at 21:08
  • $\begingroup$ Thank you for the comment. Some more questions. When I tried g3[5, 6, 7] it gave me {5,6,7} which is what I expected from the general pattern. However, g2[5, 6, 7] also gives the same result, so I am not sure what's the difference. Also g1[], g2[], just give back the same while g3[] gives back {}. Could you explain a bit more thoroughly? Am I missing something? $\endgroup$ Sep 24 '19 at 21:22
  • 4
    $\begingroup$ Konstantinos, see Blank (_), BlankSequence (__) and BlankNullSequence (___) in the docs for more details. g1 requires a single argument; so g1[] and g1[2,3] both return unevaluated. g2 requires 1 or more arguments so g2[] returns g2[]; and ... $\endgroup$
    – kglr
    Sep 24 '19 at 21:31
  • 2
    $\begingroup$ ... g3 expects 0 or more arguments so g3[] evaluates to {}, g3[1,2,3] gives {1,2,3}and g3[{1,2,3}] (one argument which is the list {1,2,3}) gives {{1,2,3}} etc. $\endgroup$
    – kglr
    Sep 24 '19 at 21:31
  • $\begingroup$ Thanks a lot once more. I did not know how to find these online. I was trying something like f[__] Mathematica and nothing was popping up. $\endgroup$ Sep 24 '19 at 21:41
10
$\begingroup$

_ matches one thing.

__ matches one or more things.

___ matches zero or more things.

$\endgroup$

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