I have a function with some optional arguments. How do I assign a value for the function when one of the optional arguments takes a particular value, regardless of any other argument values?
$\begingroup$
$\endgroup$
1
-
$\begingroup$ A clumsy way of doing it is to have a "public" function with optional arguments, whose sole purpose is to forward these arguments to a "private" function (maybe after some sanity checks). The private function can then use multiple dispatch to achieve what you want. $\endgroup$Roman– Roman2019-06-11 16:23:05 +00:00Commented Jun 11, 2019 at 16:23
Add a comment
|
1 Answer
$\begingroup$
$\endgroup$
This is what I meant in the comment above:
First, the private version of the function, with no optional arguments (all arguments must be present): multiple dispatch can be used for specific argument values, for example
Fprivate[0] = "zero";
Fprivate[1] = "one";
Fprivate[x_] := ToString[x];
Second, the public version of the function, with optional arguments: it only forwards the arguments to the private function, using a delayed assignment,
F[x_: 0] := Fprivate[x]
Try it out:
F[] (* "zero" *)
F[0] (* "zero" *)
F[1] (* "one" *)
F[2] (* "2" *)