Error: too many levels of recursion

It often happens in Maple that one procedure will call a second procedure, which in turn calls a third, and so on. Each time a procedure calls another, some information must be stored in an area of memory called the stack. This is removed when the called procedure returns. The stack has only a finite capacity, and when it is full this error message occurs. The size of the stack may vary depending on the platform, available memory in the computer, and whether or not you are using a student edition of Maple.

In many cases when the error message occurs, it is the result of an infinite recursion. For example:

> f:= n -> f(n-1)^2 + 1 mod(n+2):

> f(2);

Error, (in f) too many levels of recursion

What happens here is that to evaluate f(2) we need f(1) , and to evaluate that we need f(0) , and so on forever. No matter how much stack space we have, it will all fill up and result in an error message. A cure for this problem, if we will only want to evaluate the function on positive integers, is to assign f(0) . Then the chain of evaluations, starting at f(n) for any positive integer n , will stop at f(0) .

> f(0):= 0:

> f(10);


However, if we try f(n) for a sufficiently large n we can still fill up the stack.

> f(10000);

Error, (in f) too many levels of recursion

If you really need to perform such a calculation, it may be better to rewrite f as an iterative, rather than recursive, procedure:

> f:= proc(n)
local i, r;
r:= 0;
for i from 1 to n do
r:= r^2 + 1 mod (i+2)

> f(10000);


See also: efficiency

Maple Advisor Database R. Israel, 1997