Regarding my recent question on using a default value for a function argument when a pattern was not met yielded some interesting answers, but the general consensus was "Yes this can be done, but there are better options."
Assuming the same conditions that certain function arguments (rt
and pt
in this case) should default to zero when less than zero, the three main options are as follows:
Downvalues:
func[qi_, dei_, b_, dmin_, rt_, pt_, t_] :=
func[{qi, dei, b, dmin, Max[0, rt], Max[0, pt], t}]
func[{qi_, dei_, b_, dmin_, rt_, pt_, t_}] := (*do stuff*)
Or...
func[qi_, dei_, b_, dmin_, rt_?Negative, pt_, t_] := func[qi, dei, b, dmin, 0, pt, t]
func[qi_, dei_, b_, dmin_, rt_, pt_?Negative, t_] := func[qi, dei, b, dmin, rt, 0, t]
func[qi_, dei_, b_, dmin_, rt_, pt_, t_] :=(*do stuff*)
Scoping:
func[qi_, dei_, b_, dmin_, rt_, pt_, t_] := Module[{rtt = Max[0,rt], ptt = Max[0,pt]},
(*do stuff with rtt and ptt instead*) ]
What are the pros and cons of each function definition? Which is the most efficient?
_?Negative
doesn't do what the other does, for instance if you passrt=-3; pt=1
it will be evaluated asrt=0; pt=0
instead ofrt=0;pt=1
$\endgroup$