How to define a function whose parameter have a list with default-value
EDIT 03 / 02 / 2018
Please note that starting with version 11.2, the behavior of the pattern-matcher was changed so that the solution below no longer works. The problem with the solution below is that it makes it possible for a variable pointing at entire pattern, to get bound to something else than the expression where inner pattern variables get substituted with their default values. That is inconsistent, and that is one reason why the behavior of the pattern matcher has been modified.
--------------------------
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
*)
Give a default value to the list instead:
fun2[x_, n_: 1, a_List: {2, 3}] := x + n + Plus@@a
fun2[10]
(* 16 *)
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
*)