How to specify optional arguments that take functional values made me wonder: Can we come up with a variant of Optional
that allows to do the following:
lhs = x_;
g[lhs~HeldOptional~RandomReal[]] := x
DownValues@g
and get
{HoldPattern[g[Optional[x_, RandomReal[]]]] :> x}
Specifically, I want HeldOptional
to evaluate the left hand side like all pattern construction constructs, while leaving the right argument untouched.
The following attempt does not work:
HeldOptional~SetAttributes~HoldRest
HeldOptional[x_, y_] := Optional[x, Unevaluated@y]
This gives the DownValue
{HoldPattern[g[x_ : Unevaluated[RandomReal[]]]] :> x}
such that g[]
gives Unevaluated[RandomReal[]]
instead of a random real.
x:SetDelayed[___]/;!FreeQ[x,HeldOptional]:=...
to automate what QuantumDot suggested. $\endgroup$HeldOptional = Function[, HoldPattern@Optional[#1, #2], HoldRest]
? $\endgroup$HoldPattern
, of course! Please post an answer ;) $\endgroup$