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

1 Answer 1


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"       *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.