# Can one specify a “computed optional value”?

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...

-
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"] := ... . – march Jan 11 at 20:56
lol, yeah one could go crazy on that one – Ziofil Jan 11 at 20:58
Closely related, if not a duplicate: Can I make a default for an optional argument the value of another argument? – Emilio Pisanty Jan 11 at 21:24

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.

-
Oh yeah, this is much prettier! Thanks – Ziofil Jan 12 at 3:15