8
$\begingroup$

Sometimes you have functions with very long argument lists:

f[a_, b_, c_, d_, e_] := c

so is there a way to "name" these arguments (order insensitive) so that users can know what they're getting more easily? In pseudo-code:

f[c = "what I'm getting", a = 1, b = 2, d = 0, e = 1]

This is similar to "record syntax" in other programming languages.

$\endgroup$
  • 3
    $\begingroup$ This is precisely what options management does. You end up with f["WhatImGetting" -> 5, "TheMainThing" -> 8, "SomethingElse" -> 77] as usual with options. $\endgroup$ – Roman Jun 27 at 17:42
  • $\begingroup$ @MassDefect Your link doesn't work. $\endgroup$ – George Jun 27 at 18:17
  • 1
    $\begingroup$ Oops, thanks for letting me know. I don't know how I managed to copy it like that. This is the one I was thinking of: reference.wolfram.com/language/tutorial/… $\endgroup$ – MassDefect Jun 27 at 18:59
  • 2
    $\begingroup$ You could define f to work with associations too. $\endgroup$ – Kuba Jun 28 at 8:31
15
$\begingroup$

Here's an example for how to combine Options, OptionsPattern, and OptionValue:

First, define the available options for f and their default values:

Options[f] = {"TheMainOption" -> 0,
              "SomeOtherOption" -> 7, 
              "TheLetter" -> "A"};

Then, define the function f (here: make a list of all option values, in a particular order that is independent of the order in which the user specifies the options in the function call):

f[OptionsPattern[]] := {OptionValue["TheMainOption"],
                        OptionValue["SomeOtherOption"],
                        OptionValue["TheLetter"]}

Note that by default, OptionsPattern[] looks up the available options and defaults from the associated definition of Options[f].

Tests: the options can be given in any order, and default values are provided in the definition of Options[f]:

f[]
(*    {0, 7, "A"}    *)

f["TheLetter" -> "Z"]
(*    {0, 7, "Z"}    *)

f["TheLetter" -> "N", "SomeOtherOption" -> -2]
(*    {0, -2, "N"}    *)

Remind me what the options and defaults were for f?

Options[f]
(*    {"TheMainOption" -> 0, "SomeOtherOption" -> 7, "TheLetter" -> "A"}    *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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