Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

When I type the following code:

mus[] = 0; 
mus[x__] := First[List[x]] + mus[Rest[List[x]]]

What one would think would happen is that if,

mus[1,2,3,4] is input, the number 10 would be output. However, I get the error message,

$RecursionLimit::reclim: Recursion depth of 1024 exceeded

However if I use the following code:

lsum[{}] := 0; 
lsum[L_] := First[L] + lsum[Rest[L]]; 
sum[x__] := lsum[List[x]]

It works as I thought it should, namely if input lsum[x1,x2,x3,...,xn], the output is the sum of the xi's.

share|improve this question
@JacobAkkerboom Thank you. I think that this answers my question. –  I would like to remain anon. Nov 17 '13 at 10:01
Your function is not tail-recursive in the Mathematica sense. Have a look here and here for an explanation. –  Leonid Shifrin Nov 17 '13 at 14:35
@LeonidShifrin I have written a tail recursive variant using linkedlists. But on second thought I did not want to bother the OP :). I'll put it in my answer later, as I guess it will trigger the message again when the input is large. Leonid note that this is not a dupe, as what's causing the message in this case is just a conceptual mistake ({}=!=Unevaluated[Sequence[]]) –  Jacob Akkerboom Nov 17 '13 at 15:14
@JacobAkkerboom I wasn't one of the closers here, just left a comment. –  Leonid Shifrin Nov 17 '13 at 15:45

1 Answer 1

up vote 1 down vote accepted

Rest on a list gives you another list. Even Rest[{1}] gives you a list, i.e. the empty list {}. Therefore, in your first code, the second term with the rest in it will always make another call using the definition for mus[x__], which produces another second term, which makes at another call to mus[x__] ad infinitum.

Maybe you were thinking of a function like this

rest[first_, others___] := others

then you can write

mus[] = 0;
mus[x__] := First[List[x]] + mus[rest[x]]

I'm not saying this is good practice though :).

share|improve this answer

Your Answer


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.