# Make a function work by the keyword instead of argument position while evaluating

I have a simple function which has default values.

foo[a_: 1, b_: 2, c_: 3] := a + b + c


To evaluate it, I need to provide the arguments in the same positional order in which the function was constructed. For instance, f[1, 2, 3] or f[a = 1, b = 2, c = 3] or f[a = 1, b = 2] will be equal to 6.

However, in some situations you may want to change the value of a and c, but use the default value for b. You then must type the default value, and remember the argument positions, which becomes tedious if there are many arguments.

Is there a way to only provide function the modified arguments and evaluate it like say f[a = 1, c = 5] (make it show 8 instead of 9) such that it fills in the remaining default positions itself?

My idea was to create a keyword list and position match the argument string keys and use them as inputs. But, it also has a lot of problems: for instance, default values should be included and at times replaced in the keyword list.

– Kuba
Aug 16, 2022 at 13:09
• Yes, @kuba it looks elegant. Thanks Aug 17, 2022 at 15:31

It is possible to do with Options:

ClearAll[foo] ;
Options[foo] = {"a" -> 1, "b" -> 2, "c" -> 3} ;
foo[opts:OptionsPattern[]] := OptionValue["a"] + OptionValue["b"] + OptionValue["c"] ;

foo[]
foo["a" -> 4, "c" -> 5]

• Thank you, I am looking to update it for my problem. Aug 15, 2022 at 17:59

You could use associations as follows:

f[in_:<||>]:=With[{m=Merge[{in,<|a->1,b->2,c->3|>},First]},
m[a]+m[b]+m[c]
];


Examples:

f[]
(* 6 *)

f[<|a->4,c->5|>]
(* 11 *)