2
$\begingroup$

The standard usage of the pattern _. seems usually used in the parameter, for example, f_[a_,n_.]. I wonder if such pattern can be used to match the head of an expression. It appears syntactically legal (i.e., pass the kernel); however, I can't figure out a meaningful example that uses this mechanism. (Also, I failed to create an expression that matches some pattern like f_.[a_], etc.) So does it make sense to use it? In what circumstance?

$\endgroup$
  • $\begingroup$ The docs for Default make this look doubtful. "The necessary values for Default[f] must always be defined before _. is used as an argument of f." If _. appears as a head rather than as an argument, it seems like all bets are off. $\endgroup$ – jjc385 Mar 2 '18 at 14:55
3
$\begingroup$

It is at least possible to make a definition if there is a Symbol to attach the rule to, e.g.:

a[_.["fly"]] := "swat"

b /: _.[b] := "upset"

a[foo["fly"]]

foo[b]
"swat"

"upset"

However it both examples it could be replaced with a plain Blank[] (_) with the same apparent effect. I think this makes sense, because a head is a single expression rather than a sequence of them; you cannot have e.g. (x, y)[arg]. I suppose one might want to omit the head, e.g. have a["fly"] to evaluate and reference a Default value for the head, but based on how I understand the standard evaluation to work I would expect that to be possible either.

| improve this answer | |
$\endgroup$
  • 1
    $\begingroup$ I'm late returning to the party, but I have a few comments: (1) Did you mean "but based on how I understand the standard evaluation to work I would expect that not to be possible either" (in the last line)? $\endgroup$ – jjc385 Mar 9 '18 at 14:13
  • $\begingroup$ (2) b /: _.[b] := "upset" gives me not one but two errors -- both Message[Optional::optloose, _.]. I'm using $Version "11.2.0 for Microsoft Windows (64-bit) (September 11, 2017)". (One might say v11 is "upset" about this :p) $\endgroup$ – jjc385 Mar 9 '18 at 14:16
  • $\begingroup$ Actually, the Message[Optional::optloose, _.] seems quite descriptive -- I think I'll write it up as an answer. $\endgroup$ – jjc385 Mar 9 '18 at 14:21
  • $\begingroup$ Ok, I didn't have time to write the answer to my satisfaction, and I was confused for a while, but now I'm convinced I solved it. I was confused that the error was triggered by b /: _.[b] := "upset" but not simply by _.[b] or _.[b] :> "upset". But it is triggered by whoCares /. _.[b] :> "upset" -- the message is triggered only when a an expression 'misusing' _. or x_. is passed to a function that expects a pattern. Two such functions are ReplaceAll and TagSetDelayed. $\endgroup$ – jjc385 Mar 9 '18 at 15:25

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.