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. – masterxilo Aug 30 '16 at 21:16HeldOptional = Function[, HoldPattern@Optional[#1, #2], HoldRest]? – jkuczm Sep 11 '16 at 18:40HoldPattern, of course! Please post an answer ;) – masterxilo Sep 12 '16 at 21:46