# How to define a function whose parameter have a list with default-value

As we know,we can define a function with default-value like this:

fun1[x_, n_: 1, a_: 2, b_: 3] := x + n + a + b


In[6]:= fun1[4]

Out[6]= 10

But in my case I hope the a and b in a list,So I define it like:

fun2[x_, n_: 1, {a_: 2, b_: 3}] := x + n + a + b


In[8]:= fun2[5]

Out[8]= fun2[5]

It's failure.And I have a try this,it is failue too:

fun3[x_, n_: 1, l_List: {a_: 2, b_: 3}] := x + n + a + b


It have a strange result:

In[16]:= fun3[5]

Out[16]= 6 + a + b

-

The problem here is that the pattern you used, requires a List as a last argument in all cases. A possible workaround will be, for example:

ClearAll[fun2];
fun2[x_, n_: 1, p : {a_: 2, b_: 3} : {}] := x + n + a + b


So that

fun2[5]
fun2[5, 2, {1}]
fun2[5, 10, {1, 2}]

(*
11

11

18
*)

-
+Infinity.Very interesting. – yode Mar 5 at 18:35

Give a default value to the list instead:

fun2[x_, n_: 1, a_List: {2, 3}] := x + n + Plus@@a
fun2[10]
(* 16 *)

-
Thanks your answer.you almost solve my problem.But there a blemish still that the 2 and 3 have not its name.Of course we can use a[[1]] or a[[2]] to extract its value.Could you help me name the default-value 2 as a and the 3 as b in the fun2? – yode Mar 5 at 18:20
Fool me long time.And look forward to your response.As your answer ,your fun2 work well.Like fun2[1, 4, {7, 8}] will give a right result.But when I built a new function.fun[a_, l_list: {2, 3}] := a + Plus @@ l.The fun[1, {4, 5}] will give up to compute. – yode Mar 7 at 17:57
@yode. You need to capitalize list in the function definition: fun[a_, l_List: {2, 3}] := a + Plus @@ l works. – march Mar 7 at 18:17
God~The typo harm me deeply. – yode Mar 8 at 20:25

Other method is to add two definitions as follows:

ClearAll[fun2];
fun2[x_, n_: 1, {a_: 2, b_: 3}] := x + n + a + b
fun2[x_, n_: 1, a_: 2, b_: 3] := x + n + a + b

fun2[5]
fun2[5, 2]
fun2[5, 2, {1}]
fun2[5, 10, {1, 2}]
(*
11
12
11
18
*)

-
@yode, This is a pattern matching where fun2[5] and fun2[5, 2] match the definition fun2[x_, n_: 1, a_: 2, b_: 3] and the evaluation happens. fun2[5, 2, {1}] and fun2[5, 10, {1, 2}] match fun2[x_, n_: 1, {a_: 2, b_: 3}] and the evaluation happens also. – Algohi Mar 6 at 4:42