0

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?

Example

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

Options[f] = {a->y,b->z,c->w};
f[x_,OptionsPattern[]]:={x,OptionValue[a],OptionValue[b],OptionValue[c]}

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!

  • 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.) – Michael E2 Mar 10 '23 at 14:24
  • @MichaelE2 Oh, I had no idea it was that simple. Exactly what I was looking for. Thank you! – Learn2Burn Mar 10 '23 at 22:55

0 Answers0