1
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ @JacobAkkerboom Thank you. I think that this answers my question. $\endgroup$ – I would like to remain anon. Nov 17 '13 at 10:01
  • 1
    $\begingroup$ Your function is not tail-recursive in the Mathematica sense. Have a look here and here for an explanation. $\endgroup$ – Leonid Shifrin Nov 17 '13 at 14:35
  • $\begingroup$ @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[]]) $\endgroup$ – Jacob Akkerboom Nov 17 '13 at 15:14
  • $\begingroup$ @JacobAkkerboom I wasn't one of the closers here, just left a comment. $\endgroup$ – Leonid Shifrin Nov 17 '13 at 15:45
1
$\begingroup$

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 :).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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