Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
    
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
up vote 12 down vote accepted

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.

share|improve this answer
    
Oh yeah, this is much prettier! Thanks – Ziofil Jan 12 at 3:15

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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