2
$\begingroup$

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?

$\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$ Commented Jun 11, 2019 at 16:23

1 Answer 1

1
$\begingroup$

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"       *)
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.