Mathematica: set default value for argument to nonconstant?
Can I set the default value for a function argument to be something that's not constant? Example:
tod := Mod[AbsoluteT开发者_如何转开发ime[], 86400]
f[x_:tod] := x
In the above, 'tod' changes every time I evaluate it, but "f[]" does not. "?f" yields:
f[x_:42054.435657`11.376386798562935] := x
showing the default value was hardcoded when I created the function.
Is there a workaround here?
It seems to work if the function holds its arguments:
tod := Mod[AbsoluteTime[], 86400]
SetAttributes[f, HoldAll];
f[x_: tod] := x
In[23]:= f[]
Out[23]= 47628.994048
In[24]:= f[]
Out[24]= 47629.048193
Or you can use a construction like the following instead of a default value:
g[] := g[Mod[AbsoluteTime[], 86400]]
g[x_] := x
In[27]:= g[]
Out[27]= 47706.496195
In[28]:= g[]
Out[28]= 47707.842012
I recommend this:
f[] := f[Mod[AbsoluteTime[], 86400]]
f[x_] := x
Or equivalently, this:
f[x_:Null] := With[{x0 = If[x===Null, Mod[AbsoluteTime[], 86400], x]},
x0]
I like HoldPattern for this purpose:
f[HoldPattern[x_ : Mod[AbsoluteTime[], 86400]]] := x
In[187]:= f[1]
Out[187]= 1
In[188]:= f[]
Out[188]= 57385.091442
In[189]:= f[]
Out[189]= 57385.972670
精彩评论