5
$\begingroup$

I'm trying to do a simple thing: I want the optional argument to depend on another argument, i.e.

f[x_,y_:Subscript[m,x]] := x-y

This should give: f[z] = z-Subscript[m,z] and f[z,y] = z-y

Any idea how I can get this to work? I've tried f[x_,y_:>Subscript[m,x]] := x-y

$\endgroup$
1
  • 2
    $\begingroup$ Write separate definitions for f? That is: f[x_] := x - Subscript[m, x]; f[x_, y_] := x - y $\endgroup$ Commented Sep 14, 2022 at 17:54

1 Answer 1

9
$\begingroup$

Use two definitions:

ClearAll[f] f[x_] := x - Subscript[m, x] f[x_, y_] := x - y f[z] (* Out: z - Subscript[m, z]*) f[z, y] (* Out: -y + z *) 
$\endgroup$
1
  • 4
    $\begingroup$ In the case of a more complicated function, one could use f[x_]:=f[x,Subscript[m,x]] to avoid duplicate code. $\endgroup$ Commented Sep 14, 2022 at 18:00

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.