# How to set optional variables in Function?

When using Function, is it possible to set specific arguments to be optional? For instance, in

f = Function[{x, y}, x + y];


Can I set y to a default value (0, for example) if it is not given?

Thoughts: I know I can do

f[x_, y_: 0] := x + y


So I thought

f[x_, y_ : 0] := Function[{x, y}, x + y]


would work, but that does not seem to be the case. Any ideas?

• Your question isn't clear. The problem with f[x_, y_ : 0] := Function[{x, y}, x + y] doesn't really have anything to do with whether Function arguments can be optional (and I don't think there is a "natural" way to do that anyway). The problem is that the form of Function you're using requires symbols to be provided for the formal arguments. Evaluating f[a] will result in Function[{a, 0}, a + 0], which doesn't make sense. And without using optionality, f[1, 2] gives Function[{1, 2}, 1 + 2]. Commented Feb 20 at 20:58
• So, is your problem how to define a Function expression with SetDelayed, or is it truly about how to make Function work with optional arguments? Commented Feb 20 at 20:59
• The question is clear enough. Read again. Commented Feb 20 at 21:12
• You are nearly there. You only need correct syntax. Try: f[x_, y_ : 0] := x + y. Then f[1] results in 1 and f[1,2] results in 3. Commented Feb 20 at 21:16
• You may use "Function" but you have to remember that "Function" needs argumnets. Therefore, you would write: "f[x_, y_ : 0] = Function[{x, y}, x + y][x, y]" Commented Feb 21 at 8:07

Okay, taking your question at face value, you can do the following if you're willing to make the following assumption:

All of the arguments with default values are at the right/tail end of the argument sequence, and specifically, we rely only on argument position, not any sort of "typing".

FDefaultValues = {1, 17, 999};

f = Function[, With[{fullArgs = PadRight[{##}, 3, FDefaultValues]}, doStuff[fullArgs]]];
f[33, 44, 55]
(* doStuff[{33, 44, 55}] *)

f[33, 44]
(* doStuff[{33, 44, 999}] *)

f[33]
(* doStuff[{33, 17, 999}] *)

f[]
(* doStuff[{1, 17, 999}] *)


You can adjust this if some of the leading arguments are not optional.

### Update

It realized it would be better to parameterize the function creation with the defaults:

g[defaults_List] :=
Function[, With[{fullArgs = PadRight[{##}, 3, defaults]}, doStuff[fullArgs]]];

g1 = g[{a, b, c}]
(* Function[Null, With[{fullArgs = PadRight[{##1}, 3, {a, b, c}]}, doStuff[fullArgs]]] *)

g1[]
(* doStuff[{a, b, c}] *)

g1[11, 22]
(* doStuff[{11, 22, c}] *)

• Very interesting! I will try it later. Thanks! Commented Feb 20 at 21:43