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?
1 Answer
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.
- 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– jjc3852018-03-09 14:13:56 +00:00Commented Mar 9, 2018 at 14:13
- $\begingroup$ (2)
b /: _.[b] := "upset"gives me not one but two errors -- bothMessage[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– jjc3852018-03-09 14:16:19 +00:00Commented Mar 9, 2018 at 14:16 - $\begingroup$ Actually, the
Message[Optional::optloose, _.]seems quite descriptive -- I think I'll write it up as an answer. $\endgroup$jjc385– jjc3852018-03-09 14:21:15 +00:00Commented Mar 9, 2018 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 bywhoCares /. _.[b] :> "upset"-- the message is triggered only when a an expression 'misusing'_.orx_.is passed to a function that expects a pattern. Two such functions areReplaceAllandTagSetDelayed. $\endgroup$jjc385– jjc3852018-03-09 15:25:19 +00:00Commented Mar 9, 2018 at 15:25
Defaultmake this look doubtful. "The necessary values forDefault[f]must always be defined before_.is used as an argument off." If_.appears as a head rather than as an argument, it seems like all bets are off. $\endgroup$