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.
f
once in the pattern? What's wrong with something likef[_] | Derivative[__][f][_]
? You can always use something likeWith[{symbol = f}, ...]
if you want to writef
only once. $\endgroup$Alternatives
. I don't know of any way to match an optional head-of-a-head like you're trying to do here.Optional
orBlankNullSequence
don't work here at least. $\endgroup$OneIdentity
. $\endgroup$OneIdentity
: "In order forf[a]
to matcha
, you must use a pattern that includesOptional
." As you say, the resulting pattern then matches almost anything. $\endgroup$