How to write a `HeldOptional` variant of `Optional` that does not evaluate its second argument?
Putting together idea from question to use function with HoldRest
attribute, together with idea from QuantumDot's answer to use HoldPattern
we get:
ClearAll[HeldOptional]
HeldOptional~SetAttributes~HoldRest
HeldOptional[x_, y_] := HoldPattern@Optional[x, y]
HoldPattern
wraps whole Optional
pattern, but since function has only HoldRest
attribute, its firs argument evaluates before it's passed to held pattern.
Using HeldOptional
we get definitions equivalent to requested one:
ClearAll[lhs, g]
lhs = x_;
g[lhs~HeldOptional~RandomReal[]] := x
DownValues@g
(* {HoldPattern[g[HoldPattern[x_ : RandomReal[]]]] :> x} *)
and desired behavior:
g[a]
(* a *)
g[]
(* 0.408798 *)
g[]
(* 0.0652214 *)
g[]
(* 0.587329 *)