How can I construct a pattern that matches both f and h[f] without using the symbol f more than once in the pattern definition? That is, how can I define a pattern pattern that allows for an optional head, and returns {True, True} when used in
MatchQ[pattern] /@ {f, h[f]}
I don't want to use the alternative pattern pattern = f | h[f].
I've tried
pattern = (Identity | h)[f];
MatchQ[pattern] /@ {f, h[f]}
(* {False, True} *)
which matches h[f] but not f; it would only match an unevaluated Identity[f]. Is there a way to evaluate the pattern before application so that Identity[f] becomes f and matches?
See also here.
fonce in the pattern? What's wrong with something likef[_] | Derivative[__][f][_]? You can always use something likeWith[{symbol = f}, ...]if you want to writefonly once. – Sjoerd Smit Mar 28 '19 at 19:35Alternatives. I don't know of any way to match an optional head-of-a-head like you're trying to do here.OptionalorBlankNullSequencedon't work here at least. – Sjoerd Smit Mar 28 '19 at 19:48Default? I don't know how to use it here though as I'm trying to default the head, not an argument as usual. – Roman Mar 28 '19 at 19:50Derivative, so the focus is on the optional head issue. – Roman Mar 28 '19 at 20:13OneIdentity. – Silvia Apr 01 '19 at 21:08OneIdentity: "In order forf[a]to matcha, you must use a pattern that includesOptional." As you say, the resulting pattern then matches almost anything. – Roman Apr 03 '19 at 19:10