Main question

I want to define a function g that calls a function f. g has optional arguments, some of which it passes on to f when f is called. However, I want the default values of the options for gto be different than the defaults f. How do I define gefficiently?


Suppose I have a function f[x] with optional arguments a, b, and c defined below:

Options[f] = {a->y,b->z,c->w};

Evaluating f[x] yields {x, y, z, w}. Evaluating f[x,a->0,c-> 2] yields {x, 0, z, 2} etc.

Now I want a function g[x] whose output is f[2 x]. Additionally, I want gto have the same optional arguments as f, but with different default values:{a->2,b->4,c->6}. How do I define g efficiently?

The code below doesn't work:

Options[g] = {a->2,b->4,c->6}
g[x_,opts:OptionsPattern[]]:= f[2 x,opts]

Evaluating g[x] yields {2 x, y, z, w}. Evaluating g[x, b -> 10] yields {2 x, y, 10, w}. Clearly, the default options for g are effectively the default options for f, which is not what we wanted.

The code below does work, but is clunky:

Options[g] = {a -> 2, b -> 4, c -> 6};
g[x_, OptionsPattern[]] := 
 f[2 x, Sequence @@ ((#[[1]] -> OptionValue[#[[1]]]) & /@ Options[f])]

Now, Evaluatingg[x] yields {2 x, 2, 4, 6}, and g[x,b->10] yields {2 x, 2, 10, 6} as desired. But it feels like there must be a simpler way to write the code for g.

Any help is greatly appreciated!

  • $\begingroup$ g[x_, opts : OptionsPattern[]] := f[2 x, opts, Options[g]]? OptionsPattern is fairly robust for catenating options and lists of options. (First occurrence takes precedence over later ones.) $\endgroup$
    – Michael E2
    Mar 10, 2023 at 14:24
  • $\begingroup$ @MichaelE2 Oh, I had no idea it was that simple. Exactly what I was looking for. Thank you! $\endgroup$
    – Learn2Burn
    Mar 10, 2023 at 22:55


Your Answer

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

Browse other questions tagged or ask your own question.