function construction - Can I make a default for an optional argument the value of another argument?
I'd like to define a function with several optional arguments, some of which default to the value supplied for other arguments. For example, I'd like to be able to write something like
f[x_, y_: 0, z_: y] := {x, y, z}
and have
{f[1, 2], f[1]}
produce
{{1, 2, 2}, {1, 0, 0}}
Instead I get
{{1, 2, y}, {1, 0, y}}
Can I make a default for an optional argument the value of another argument? If not, what's the best approach for accomplishing this?
Answer
You can't easily do this with optional arguments (but see Leonid's answer for a work around), but you can use the fact that you can have multiple definitions for a given function:
f[x_, y_:0] := {x, y, y}
f[x_, y_, z_] := {x, y, z}
will do what you want.
For further use of this style you could also do this as:
f[x_] := {x, 0, 0}
f[x_, y_] := {x, y, y}
f[x_, y_, z_] := {x, y, z}
which makes the "pattern" of your function even more explicit
Comments
Post a Comment