7
$\begingroup$

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.

$\endgroup$
2
  • 1
    $\begingroup$ Does this answer your question: 241295? $\endgroup$
    – Kuba
    Aug 16, 2022 at 13:09
  • $\begingroup$ Yes, @kuba it looks elegant. Thanks $\endgroup$
    – Rupesh
    Aug 17, 2022 at 15:31

2 Answers 2

9
$\begingroup$

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]
$\endgroup$
1
  • $\begingroup$ Thank you, I am looking to update it for my problem. $\endgroup$
    – Rupesh
    Aug 15, 2022 at 17:59
4
$\begingroup$

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 *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.