7
$\begingroup$

I would like to write a function with an optional argument, which if absent should not be a default value, but rather a computed value. What I mean is the following [warning this code does not work, it's just for a descriptive purpose]

f[var1_, var2_ : g[var1] ] := etc...

where g is some function. So far I have tried using a silly default value for var2 and an if statement:

f[var1_, var2_ : 123456789] := If[ var2 == 123456789 , var2 = g[var1] , etc...]

which works, but is ugly...

$\endgroup$
  • $\begingroup$ I kind of like your approach, actually, but perhaps to be safe, your "default" value could be something that no chance of being an input to f, like, say, f[var1_, var2_ : "Pileated"] := ... . $\endgroup$ – march Jan 11 '16 at 20:56
  • $\begingroup$ lol, yeah one could go crazy on that one $\endgroup$ – Ziofil Jan 11 '16 at 20:58
  • $\begingroup$ Closely related, if not a duplicate: Can I make a default for an optional argument the value of another argument? $\endgroup$ – Emilio Pisanty Jan 11 '16 at 21:24
12
$\begingroup$

The simplest way is simply to define the two-argument case,

f[var1_, var2_] := ...

and then the one-argument case as

f[var1_] := f[var1, g[var1]]

Of course, if things get fancy, this sort of scheme will stretch but it can eventually break. For more flexible uses, see Leonid Shiffrin's answer to this similar question.

$\endgroup$
  • $\begingroup$ Oh yeah, this is much prettier! Thanks $\endgroup$ – Ziofil Jan 12 '16 at 3:15

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.