Perhaps this is poor programming on my part, but I would like to create a function that uses a variable as an optional parameter:
var = 2;
f[a_:var] := {a}
The desired output would be:
f[]
(* {2} *)
var = 5;
f[]
(* {5} *)
However the optional a
maintains the value of var
when f
was defined:
var = 2;
f[a_:var] := {a}
var = 5;
f[]
(* {2} *)
f[5]
(* {5} *)
I can work around this somewhat by making the optional value dynamic:
var = 2;
f[a_:Dynamic[var]] := {a}
f[];
(* {2} *)
var = 5;
(* Above output updates to 5 *)
I can imagine having some fun with this type of behavior, but it is not what I want at the moment. Is it possible to set an optional parameter that can be updated? I'll also happily accept an answer that tells me why this would be a bad idea.
f[x_]:={x}; f[]:={a};
$\endgroup$var
has any value, or useBlock
, such asBlock[{var}, f[a_:var]:={a}]
. See also this answer and a discussion in comments below it. $\endgroup$Default
appears to allow variable values, but it does not. You may already know this, but it's tripped up quite a few users I believe. Also, I see that Simon (I miss his participation) posted effectively the same method that Leonid just showed in answer to that old question of mine. $\endgroup$