Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 7 down vote accepted

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
*)
share|improve this answer
    
+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 *)
share|improve this answer
    
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
*)
share|improve this answer
    
Could you add some explanation what about this effect??? – yode Mar 5 at 22:46
    
@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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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