# How to make the third parameter optional and adding some condition?

I have a function as follows. The function has 3 parameters. Now I would like to make the third parameter i optional. So you call call it like myFunc[3, {1,2,3},1] or myFunc[3, {1,2,3}].

myFunc[n_Integer, list_?VectorQ, i_] := Module[{x, y},
x = ToExpression["x" <> IntegerString[{i}]];
y = ToExpression["y" <> IntegerString[{i}]];]


And I would like to add a condition that if there is no third parameter then only do the ToExpression["x"] and ToExpression["y"] below without joining the string IntegerString[{i}]:

 x = ToExpression["x"];
y = ToExpression["y"];


Is there a neat way to do this?

The above is part of this funciton: I tried the suggestion adding a function with two parameters but somehow it add an index 0 like x0, y0 when you omit the third parameter.

Module[{M, idx, idxc, idx1, idx1c, Y, Yc, x, y, z},
idx = Pick[Range[Length[list]],
UnitStep[list - 1] UnitStep[n - list], 1];
M = ConstantArray[0, {n, n}];
idx1 = list[[idx]];
x = ToExpression["x" <> IntegerString[{i}]];
y = ToExpression["y" <> IntegerString[{i}]];
z = ToExpression["z"];
Y = {{1/z, 0, -(1/z)}, {x, 1/y, -z - 1/y}, {-(1/z) - x, -(1/y),
1/z + z + 1/y}};
Yc = {{1/z + y + 1/z, -(1/x) - y - 1/z}, {-(1/y) - z - (1/y),
1/x + y + 1/z}};
If[Length[list] == 2, M[[idx1, idx1]] = Yc[[idx, idx]],
M[[idx1, idx1]] = Y[[idx, idx]]];
M]

• actually it's a small part of another function so I tried that but it added x0, y0. Let me added more detail about my function. Jun 3, 2021 at 15:54
• Does simply using myFunc[n_Integer, list_?VectorQ, i___] (i.e. BlankNullSequence) in the i variable works as needed? Jun 3, 2021 at 16:24

You can define more than one interface for a function:

myFunc[n_Integer, list_?VectorQ, i_] := Module[{x, y},
x = ToExpression["x" <> IntegerString[{i}]];
y = ToExpression["y" <> IntegerString[{i}]];
restoffunction[n, list, x, y]]

myFunc[n_Integer, list_?VectorQ] := Module[{x, y},
x = ToExpression["x"];
y = ToExpression["y"];
restoffunction[n, list, x, y]]


Mathematica will then choose whichever interface fits the calling case. By using a common trunk restoffunction, code duplication is reduced.

What you're asking is called Optional. You can provide a default value, then inside your function check whether the default value is passed or not.

## Code

Here, the default value is Missing["notFound"]. z introduced to hold natural value for your operation ("") and if i is not the same as default, then IntegerString will be applied.

myFunc[n_Integer, list_?VectorQ, i_ : Missing["notFound"]] :=
Module[{x, y, z = ""},
If[! SameQ[i, Missing["notFound"]], z = IntegerString[{i}]];

x = ToExpression["x" <> z];
y = ToExpression["y" <> z];
]

• If[MissingQ[i], ... would be simpler. Jun 3, 2021 at 16:35
• @Roman thanks for your feedback, Because solution's Missing has a custom message in order to be distinguishable from other Missing, I used SameQ. Jun 3, 2021 at 17:50