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$
4
  • $\begingroup$ @JacobAkkerboom Thank you. I think that this answers my question. $\endgroup$ Commented Nov 17, 2013 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$ Commented Nov 17, 2013 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$ Commented Nov 17, 2013 at 15:14
  • $\begingroup$ @JacobAkkerboom I wasn't one of the closers here, just left a comment. $\endgroup$ Commented Nov 17, 2013 at 15:45

1 Answer 1

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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.