Mathematica: set default value for argument to nonconstant?

浪子不回头ぞ 提交于 2019-12-04 09:09:16

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]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!