What does _. mean in patterns? [closed]
What does _. mean in patterns? [closed]
Here is a quick one, hopefully. I searched through different tutorials and documentation articles but haven't been able to find anything yet.
What does _.
mean? As in _,_.
as opposed to _,_
or _,_,_.
as opposed to _,_,_
?
_.
_,_.
_,_
_,_,_.
_,_,_
Thanks!
This question appears to be off-topic. The users who voted to close gave this specific reason:
$begingroup$
@xzczd Thanks! I didn't actually know about that!
$endgroup$
– Jmeeks29ig
Sep 13 '18 at 17:30
2 Answers
2
FullForm
will show you how an expression is really interpreted,
FullForm
In[5]:= FullForm[_.]
Out[5]= Optional[Blank]
This tells you you need to look at Optional
and Blank
to understand this particular syntax.
Optional
Blank
This is especially important for infix operators like this, because for some the F1 documentation search doesn't bring up a relevant page. Take the expression
x // f
or
f @ x
Running FullForm
on either of these returns f[x]
- telling you immediately what the notation means. This is good because if you highlight the @
or //
and hit F1 you will find Prefix
and Postfix
, which aren't very helpful for understanding what those symbols mean. But FullForm
will tell you how your syntax is interpreted by the front end, and what it is sent to the kernel as.
FullForm
f[x]
@
//
Prefix
Postfix
FullForm
$begingroup$
Thanks! I'm still learning some of the basics, I should have thought to use FullForm :)
$endgroup$
– Jmeeks29ig
Sep 13 '18 at 17:36
$begingroup$
@Jmeeks29ig - glad to help!
$endgroup$
– Jason B.
Sep 14 '18 at 1:45
$begingroup$
I messed up when first commenting on this, so I cannot claim that the answer is trivial (and I wish the question hadn't been closed). It would be useful to include a few examples about how
Optional
is used. So far we learnt that _.
is one shorthand for Optional
. The more common shorthand is :
, e.g. x_ : defaultValue
. With this pattern, the name x
will be assigned the explicitly written defaultValue
. With f[x_.]
, the value of x
will be taken from Default[f]
. Here it is necessary to have the enclosing symbol f
.$endgroup$
– Szabolcs
Sep 14 '18 at 11:59
Optional
_.
Optional
:
x_ : defaultValue
x
defaultValue
f[x_.]
x
Default[f]
f
I'm not sure if this fully answers the question I posted, but after some more searching, I have discovered that it seems like _.
evaluates to Optional
, at least when using ReplaceAll
. An example will be better than words:
_.
Optional
ReplaceAll
_, _. /. _Blank -> g
evaluates to:
g, Optional[g]
I know this is not a full answer, but hopefully it is at least partially helpful.
$begingroup$
"I searched through different tutorials and documentation articles but haven't been able to find anything yet." Then you haven't yet learned the correct usage of document: i.stack.imgur.com/RVvvv.gif
$endgroup$
– xzczd
Sep 13 '18 at 17:28