9

When evaluatingf[x_:x0] := x, x0 will be evaluated, regardless of the HoldAll attribute of SetDelayed.

Why the second argument of Optional is evaluated in a non-standard manner?

xzczd
  • 65,995
  • 9
  • 163
  • 468
bcegkmqs23
  • 742
  • 3
  • 15

1 Answers1

9

From the "Details" of the docs for HoldPattern

The left-hand sides of rules are usually evaluated, as are parts of the left-hand sides of assignments. You can use HoldPattern to stop any part from being evaluated.

Application:

ClearAll[f];
f[HoldPattern[x_: x0]] := x;

x0 = 7;

f[5]
f[]
(*
  5
  7
*)

Block[{x0 = 3},
 f[]
 ]
(*  3  *)
Michael E2
  • 235,386
  • 17
  • 334
  • 747