Find limit of recursion: Difference between revisions

added RPL
(added RPL)
 
(16 intermediate revisions by 10 users not shown)
Line 13:
Reading the current stack pointer is unreliable, as there is no requirement that the stack be "aligned" in any way. Unlike the 8086 and Z80, which require all pushes/pops to be exactly two bytes, the 6502's stack will likely contain both 1 byte registers and 2 byte return addresses. It's much easier to use a stack canary. Pick a value that is unlikely to be used in your program.
 
<langsyntaxhighlight lang="6502asm">;beginning of your program
lda #$BE
sta $0100
Line 27:
lda $0100 ;if this no longer equals $BE the stack has overflowed
cmp #$BE
bne StackHasOverflowed</langsyntaxhighlight>
 
=={{header|8080 Assembly}}==
Line 51:
at run-time, at the cost of some overhead per call.
 
<langsyntaxhighlight lang="8080asm"> org 100h
lxi b,0 ; BC holds the amount of calls
call recur ; Call the recursive routine
Line 99:
;;; If the guard is overwritten, the stack has overflowed.
GUARD: equ $+2 ; Make sure it is not a valid return address
guard: dw GUARD</langsyntaxhighlight>
 
{{out}}
Line 120:
of calls you can make before the stack is full (and would overwrite your program).
 
<langsyntaxhighlight lang="8080asm"> org 100h
lxi h,-top ; Subtract highest used location from stack pointer
dad sp
Line 159:
;;; This means anything from this place up to SP is free for the
;;; stack.
top: equ $ </langsyntaxhighlight>
 
{{out}}
Line 166:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun recursion-limit (x)
(if (zp x)
0
(prog2$ (cw "~x0~%" x)
(1+ (recursion-limit (1+ x))))))</langsyntaxhighlight>
 
{{out}} (trimmed):
Line 187:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Recursion_Depth is
Line 199:
begin
Put_Line ("Recursion depth on this system is" & Integer'Image (Recursion (1)));
end Test_Recursion_Depth;</langsyntaxhighlight>
Note that unlike some solutions in other languages this one does not crash (though usefulness of this task is doubtful).
 
Line 218:
=={{header|ALGOL 68}}==
The depth of recursion in Algol 68 proper is unlimited. Particular implementations will reach a limit, if only through exhaustion of storage and/or address space and/or time before power failure. If not time limited, the depth reached depends very much on what the recursive routine needs to store on the stack, including local variables if any. The simplest recursive Algol68 program is:
<langsyntaxhighlight lang="algol68">PROC recurse = VOID : recurse; recurse</langsyntaxhighlight>
This one-liner running under Algol68 Genie and 64-bit Linux reaches a depth of 3535 with the shell's default stack size of 8Mbytes and 28672 when set to 64Mbytes,
as shown by the following output. From this we can deduce that Genie does not implement tail recursion. The --trace option to a68g prints a stack trace when the program crashes; the first two commands indicate the format of the trace, the third counts the depth of recursion with the default stack size and the fourth shows the result of octupling the size of the stack.
Line 255:
===Test 1===
A basic test for Applescript, which has a notoriously shallow recursion stack.
<langsyntaxhighlight lang="applescript">-- recursionDepth :: () -> IO String
on recursionDepth()
script go
Line 274:
recursionDepth()
end run</langsyntaxhighlight>
{{Out}}
<pre>"Recursion limit encountered at 502"</pre>
Line 280:
===Test 2===
We get a fractionally higher (and arguably purer) result by deriving the highest Church Numeral (Church-encoded integer) that can be represented using AppleScript:
<langsyntaxhighlight lang="applescript">-- HIGHEST CHURCH NUMERAL REPRESENTABLE IN APPLESCRIPT ?
 
-- (This should be a good proxy for recursion depth)
Line 373:
on succ(x)
1 + x
end succ</langsyntaxhighlight>
{{Out}}
<pre>"The highest Church-encoded integer representable in Applescript is 571"</pre>
Line 384:
Testing with no local variables and with an external 'try' statement, the maximum recursion depth possible appears to be 733. (732 if the code below's run as an applet instead of in an editor or from the system script menu.) So, depending on what a script actually does, the limit can be anything between <502 and 733. In practice, it's very difficult for well written AppleScript code to run out of stack.
 
<langsyntaxhighlight lang="applescript">global i
 
on recursion()
Line 399:
-- display dialog result -- Uncomment to see the result if running as an applet.
end try
end run</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"Recursion limit encountered at 733"</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">recurse: function [x][
print x
recurse x+1
]
 
recurse 0</langsyntaxhighlight>
 
{{out}}
Line 425:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Recurse(0)
 
Recurse(x)
Line 431:
TrayTip, Number, %x%
Recurse(x+1)
}</langsyntaxhighlight>
 
Last visible number is 827.
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">;AutoIt Version: 3.2.10.0
$depth=0
recurse($depth)
Line 442:
ConsoleWrite($depth&@CRLF)
Return recurse($depth+1)
EndFunc</langsyntaxhighlight>
Last value of $depth is 5099 before error.
Error: Recursion level has been exceeded - AutoIt will quit to prevent stack overflow.
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk"># syntax: GAWK -f FIND_LIMIT_OF_RECURSION.AWK
#
# version depth messages
Line 468:
if (n > 999999) { return }
x()
}</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 475:
In Axe 1.2.2 on a TI-84 Plus Silver Edition, the last line this prints before hanging is 12520. This should be independent of any arguments passed since they are not stored on the stack.
 
<langsyntaxhighlight lang="axe">RECURSE(1)
Lbl RECURSE
.Optionally, limit the number of times the argument is printed
Disp r₁▶Dec,i
RECURSE(r₁+1)</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
Each GOSUB consumes 6 bytes of stack space and when more than 25 levels have been reached and an <code>?OUT OF MEMORY ERROR</code> message is displayed.
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic"> 100 PRINT "RECURSION DEPTH"
110 PRINT D" ";
120 LET D = D + 1
130 GOSUB 110"RECURSION</langsyntaxhighlight>
{{out}}
<pre>RECURSION DEPTH
Line 496:
Utterly dependent on the stack size and RAM available to the process.
 
<langsyntaxhighlight lang="freebasic">' Recursion limit
FUNCTION recurse(i)
PRINT i
Line 503:
END FUNCTION
 
extraneous = recurse(0)</langsyntaxhighlight>
 
{{out}}
Line 517:
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="freebasic">function Recursion(i)
print i
ext = Recursion(i + 1)
Line 523:
end function
 
ext = Recursion(0)</langsyntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">10 sub recursion(n)
20 print n
30 recursion(1 + n)
40 end sub
50 recursion(0)
60 end</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<langsyntaxhighlight lang="freebasic">sub sisyphus( n as ulongint )
print n
sisyphus( 1 + n )
end sub
sisyphus(0)</langsyntaxhighlight>
{{out}}
<pre>
Line 542 ⟶ 551:
Segmentation fault (core dumped)
</pre>
 
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public Sub Main()
Recursion(0)
End
 
Sub Recursion(n As Long)
 
Print n
Recursion(1 + n)
 
End Sub</syntaxhighlight>
 
==={{header|GW-BASIC}}===
<langsyntaxhighlight lang="gwbasic">10 N#=0
20 N# = N# + 1
30 LOCATE 1,1:PRINT N#
40 GOSUB 20</langsyntaxhighlight>
{{out}}
<pre>
33
Out of memory in 20.</pre>
 
==={{header|Minimal BASIC}}===
<syntaxhighlight lang="qbasic">10 LET N = 0
20 LET N = N + 1
30 PRINT N
40 GOSUB 20
50 END</syntaxhighlight>
{{out}}
<pre> 257
40: error: stack overflow</pre>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
The [[#GW_BASIC|GW BASIC]] solution works without any changes.>
 
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
<langsyntaxhighlight lang="qbasic">FUNCTION Recursion (i)
PRINT i
ext = Recursion(i + 1)
Line 561 ⟶ 598:
END FUNCTION
 
ext = Recursion(0)</langsyntaxhighlight>
 
==={{header|Quite BASIC}}===
<syntaxhighlight lang="qbasic">10 LET N = 0
20 LET N = N + 1
30 PRINT N
40 GOSUB 20</syntaxhighlight>
 
==={{header|Sinclair ZX81 BASIC}}===
The only limit is the available memory.
<langsyntaxhighlight lang="basic">10 LET D=0
20 GOSUB 30
30 PRINT AT 0,0;D
40 LET D=D+1
50 GOSUB 30</langsyntaxhighlight>
{{out}}
Run with 1k of RAM:
Line 578 ⟶ 621:
 
==={{header|Tiny BASIC}}===
<langsyntaxhighlight Tinylang="tiny BASICbasic">10 LET N = -32767
20 LET M = 0
30 LET N = N + 1
Line 584 ⟶ 627:
50 IF N = 32767 THEN PRINT M," x 2^16"
60 IF N = 32767 THEN LET N = -N
70 GOSUB 30</langsyntaxhighlight>
{{out}}
<pre>1 x 2^16
Line 600 ⟶ 643:
{{works with|BASIC256}}
{{works with|QBasic}}
<langsyntaxhighlight lang="qbasic">FUNCTION Recursion (i)
PRINT i
LET ext = Recursion(i + 1)
Line 607 ⟶ 650:
 
LET ext = Recursion(0)
END</langsyntaxhighlight>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<langsyntaxhighlight lang="xbasic">PROGRAM "Find limit of recursion"
 
DECLARE FUNCTION Entry ()
Line 625 ⟶ 668:
 
END FUNCTION
END PROGRAM</langsyntaxhighlight>
 
==={{header|Yabasic}}===
<langsyntaxhighlight lang="freebasic">sub Recursion(i)
print i
Recursion(i + 1)
end sub
 
Recursion(0)</langsyntaxhighlight>
 
==={{header|ZX Spectrum Basic}}===
On the ZX Spectrum recursion is limited only by stack space. The program eventually fails, because the stack is so full that there is no stack space left to make the addition at line 110:
<langsyntaxhighlight lang="zxbasic">10 LET d=0: REM depth
100 PRINT AT 1,1; "Recursion depth: ";d
110 LET d=d+1
120 GO SUB 100: REM recursion
130 RETURN: REM this is never reached
200 STOP</langsyntaxhighlight>
{{out}}(from a 48k Spectrum):
<pre> Recursion depth: 13792
Line 650 ⟶ 693:
MUNG.CMD is a commandline tool written in DOS Batch language. It finds the limit of recursion possible using CMD /C.
 
<langsyntaxhighlight lang="dos">@echo off
set /a c=c+1
echo [Depth %c%] Mung until no good
cmd /c mung.cmd
echo [Depth %c%] No good
set /a c=c-1</langsyntaxhighlight>
 
Result (abbreviated):
Line 672 ⟶ 715:
If one uses <code>call</code> rather than <code>CMD/C</code>, the call depth is much deeper but ends abruptly and can't be trapped.
 
<langsyntaxhighlight lang="dos">@echo off
set /a c=c+1
echo [Depth %c%] Mung until no good
call mung.cmd
echo [Depth %c%] No good
set /a c=c-1</langsyntaxhighlight>
 
Result (abbreviated):
Line 691 ⟶ 734:
You also get the exact same results when calling mung internally, as below
 
<langsyntaxhighlight lang="dos">@echo off
set c=0
:mung
Line 698 ⟶ 741:
call :mung
set /a c=c-1
echo [Level %c%] No good</langsyntaxhighlight>
 
Setting a limit on the recursion depth can be done like this:
 
<langsyntaxhighlight lang="dos">@echo off
set c=0
:mung
Line 710 ⟶ 753:
call :mung %c%
set /a c=%1-1
echo [Level %c%] No good</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> PROCrecurse(1)
END
Line 719 ⟶ 762:
IF depth% MOD 100 = 0 PRINT TAB(0,0) depth%;
PROCrecurse(depth% + 1)
ENDPROC</langsyntaxhighlight>
{{out}} from BBC BASIC for Windows with default value of HIMEM:
<pre>
Line 732 ⟶ 775:
Most interpreters allocate their stack on the global heap, so the size of the stack will depend on available memory, and on a modern system you're likely to run out of patience long before you run out of memory. That said, there have been some interpreters with a fixed stack depth - as low as 199 even - but that isn't a common implementation choice.
 
<langsyntaxhighlight lang="befunge">1>1#:+#.:_@</langsyntaxhighlight>
 
=={{header|BQN}}==
 
Tested with the [[CBQN]] REPL on Ubuntu Linux.
<langsyntaxhighlight lang="bqn"> {𝕊1+•Show 𝕩}0
0
1
Line 746 ⟶ 789:
Error: Stack overflow
at {𝕊1+•Show 𝕩}0
</syntaxhighlight>
</lang>
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">rec=.out$!arg&rec$(!arg+1)</langsyntaxhighlight>
 
Observed recursion depths:
Line 757 ⟶ 800:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void recurse(unsigned int i)
Line 769 ⟶ 812:
recurse(0);
return 0;
}</langsyntaxhighlight>
 
Segmentation fault occurs when i is 523756.
Line 780 ⟶ 823:
 
The following code may have some effect unexpected by the unwary:
<langsyntaxhighlight Clang="c">#include <stdio.h>
 
char * base;
Line 802 ⟶ 845:
recur();
return 0;
}</langsyntaxhighlight>
With GCC 4.5, if compiled without -O2, it segfaults quickly; if <code>gcc -O2</code>, crash never happens, because the optimizer noticed the tail recursion in recur() and turned it into a loop!
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
class RecursionLimit
{
Line 819 ⟶ 862:
Recur(i + 1);
}
}</langsyntaxhighlight>
 
Through debugging, the highest I achieve is 14250.
Line 826 ⟶ 869:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
Line 839 ⟶ 882:
recurse(0);
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">
=> (def *stack* 0)
=> ((fn overflow [] ((def *stack* (inc *stack*))(overflow))))
Line 848 ⟶ 891:
=> *stack*
10498
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol">identification division.
program-id. recurse.
data division.
Line 901 ⟶ 944:
*> room for a better-than-abrupt death here.
exit program.</langsyntaxhighlight>
Compiled with <pre>cobc -free -x -g recurse.cbl</pre> gives, after a while,
<pre>...
Line 933 ⟶ 976:
 
{{works with|OpenCOBOL}}
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. recurse RECURSIVE.
DATA DIVISION.
Line 957 ⟶ 1,000:
EXIT PROGRAM.
END PROGRAM recurse-sub.
END PROGRAM recurse. </langsyntaxhighlight>
 
Compiled with <pre>cobc -x -g recurse.cbl</pre> gives
Line 971 ⟶ 1,014:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
recurse = ( depth = 0 ) ->
try
Line 979 ⟶ 1,022:
 
console.log "Recursion depth on this system is #{ do recurse }"
</syntaxhighlight>
</lang>
 
{{out}} Example on [http://nodejs.org Node.js]:
Line 988 ⟶ 1,031:
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">
(defun recurse () (recurse))
(trace recurse)
(recurse)
</syntaxhighlight>
</lang>
 
{{out}} This test was done with clisp under cygwin:
Line 1,008 ⟶ 1,051:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="crystal">def recurse(counter = 0)
puts counter
recurse(counter + 1)
Line 1,014 ⟶ 1,057:
 
recurse()
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,023 ⟶ 1,066:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.c.stdio;
 
void recurse(in uint i=0) {
Line 1,032 ⟶ 1,075:
void main() {
recurse();
}</langsyntaxhighlight>
With the DMD compiler, using default compilation arguments, the stack overflows at 51_002.
 
Line 1,041 ⟶ 1,084:
=={{header|Dc}}==
Tail recursion is optimized into iteration by GNU dc, so I designed a not tail recursive function, summing all numbers up to n:
<langsyntaxhighlight lang="dc">## f(n) = (n < 1) ? n : f(n-1) + n;
[q]sg
[dSn d1[>g 1- lfx]x Ln+]sf
Line 1,047 ⟶ 1,090:
 
65400 lhx
65600 lhx</langsyntaxhighlight>
With the standard Ubuntu stack size limit 8MB I get
{{out}}
Line 1,064 ⟶ 1,107:
=={{header|Delphi}}==
{{works with|Delphi|2010 (and probably all other versions)}}
<langsyntaxhighlight lang="delphi">program Project2;
{$APPTYPE CONSOLE}
uses
Line 1,084 ⟶ 1,127:
Writeln('Press any key to Exit');
Readln;
end.</langsyntaxhighlight>
 
{{out}}
Line 1,093 ⟶ 1,136:
Recursion limit is a parameter of script execution, which can be specified independently from the stack size to limit execution complexity.
 
<langsyntaxhighlight lang="delphi">var level : Integer;
 
procedure Recursive;
Line 1,106 ⟶ 1,149:
Recursive;
 
Println('Recursion Level is ' + IntToStr(level));</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
{{untested|Déjà Vu}}
<langsyntaxhighlight lang="dejavu">rec-fun n:
!. n
rec-fun ++ n
 
rec-fun 0</langsyntaxhighlight>
This continues until the memory is full, so I didn't wait for it to finish.
Currently, it should to to almost 3 million levels of recursion on a machine with 1 GB free.
Line 1,125 ⟶ 1,168:
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>func recurse i . .
proc recurse i . .
print i
call recurseif i +mod 110 = 0
print i
.
recurse i + 1
.
call recurse 0</lang>1
</syntaxhighlight>
<pre>
0
.
.
9100
9999
InternalError: too much recursion
----------------------------
| max call depth of exceeded |
----------------------------
</pre>
 
Line 1,144 ⟶ 1,188:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight lang="lisp">(defun my-recurse (n)
(my-recurse (1+ n)))
(my-recurse 1)
=>
enters debugger at (my-recurse 595),
per the default max-lisp-eval-depth 600 in Emacs 24.1</langsyntaxhighlight>
 
Variable <code>max-lisp-eval-depth</code>[http://www.gnu.org/software/emacs/manual/html_node/elisp/Eval.html#index-max_002dlisp_002deval_002ddepth-539] is the maximum depth of function calls and variable <code>max-specpdl-size</code>[http://www.gnu.org/software/emacs/manual/html_node/elisp/Local-Variables.html#index-max_002dspecpdl_002dsize-614] is the maximum depth of nested <code>let</code> bindings. A function call is a <code>let</code> of the parameters, even if there's no parameters, and so counts towards <code>max-specpdl-size</code> as well as <code>max-lisp-eval-depth</code>.
Line 1,161 ⟶ 1,205:
A tail-recursive function will run indefinitely without problems (the integer will overflow, though).
 
<langsyntaxhighlight lang="fsharp">let rec recurse n =
recurse (n+1)
 
recurse 0</langsyntaxhighlight>
The non-tail recursive function of the following example crashed with a <code>StackOverflowException</code> after 39958 recursive calls:
 
<langsyntaxhighlight lang="fsharp">let rec recurse n =
printfn "%d" n
1 + recurse (n+1)
 
recurse 0 |> ignore</langsyntaxhighlight>
 
=={{header|Factor}}==
Factor is tail-call optimized, so the following example will run without issue. In fact, Factor's iterative combinators such as <code>map</code>, <code>each</code>, and <code>times</code> are written in terms of tail recursion.
<langsyntaxhighlight lang="factor">: recurse ( n -- n ) 1 + recurse ;
 
0 recurse</langsyntaxhighlight>
The following non-tail recursive word caused a call stack overflow error after 65518 recursive calls in the listener.
<langsyntaxhighlight lang="factor">SYMBOL: depth
 
: fn ( n -- n ) depth inc 1 + fn 1 + ;
 
[ 0 fn ] try
depth get "Recursion depth on this system is %d.\n" printf</langsyntaxhighlight>
{{out}}
<pre>
Line 1,195 ⟶ 1,239:
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">
Func Sisyphus(n)=!!n;Sisyphus(n+1).
Sisyphus(0)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,211 ⟶ 1,255:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: munge ( n -- n' ) 1+ recurse ;
 
: test 0 ['] munge catch if ." Recursion limit at depth " . then ;
 
test \ Default gforth: Recursion limit at depth 3817</langsyntaxhighlight>
 
Or you can just ask the system:
 
<langsyntaxhighlight lang="forth">s" return-stack-cells" environment? ( 0 | potential-depth-of-return-stack -1 )</langsyntaxhighlight>
 
Full TCO is problematic, but a properly tail-recursive call is easy to add to any Forth. For example, in SwiftForth:
 
<langsyntaxhighlight lang="forth">: recur; [ last 2 cells + literal ] @ +bal postpone again ; immediate
 
: test dup if 1+ recur; then drop ." I gave up finding a limit!" ;
 
1 test</langsyntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">program recursion_depth
 
implicit none
Line 1,248 ⟶ 1,292:
end subroutine recurse
 
end program recursion_depth</langsyntaxhighlight>
{{out}} (snipped):
<pre>208914
Line 1,264 ⟶ 1,308:
=={{header|GAP}}==
The limit is around 5000 :
<langsyntaxhighlight lang="gap">f := function(n)
return f(n+1);
end;
Line 1,280 ⟶ 1,324:
 
# quit "brk mode" and return to GAP
quit;</langsyntaxhighlight>
This is the default GAP recursion trap, see [http://www.gap-system.org/Manuals/doc/htm/ref/CHAP007.htm#SECT010 reference manual, section 7.10]. It enters "brk mode" after multiples of 5000 recursions levels. On can change this interval :
<langsyntaxhighlight lang="gap">SetRecursionTrapInterval(100000);
# No limit (may crash GAP if recursion is not controlled) :
SetRecursionTrapInterval(0);</langsyntaxhighlight>
 
=={{header|gnuplot}}==
<langsyntaxhighlight lang="gnuplot"># Put this in a file foo.gnuplot and run as
# gnuplot foo.gnuplot
 
Line 1,297 ⟶ 1,341:
print "try recurse ", try
print recurse(try)
reread</langsyntaxhighlight>
 
Gnuplot 4.6 has a builtin <code>STACK_DEPTH</code> limit of 250, giving
Line 1,315 ⟶ 1,359:
The default can be changed by [https://golang.org/pkg/runtime/debug#SetMaxStack <code>SetMaxStack</code>] in the <code>runtime/debug</code> package. It is documented as "useful mainly for limiting the damage done by goroutines that enter an infinite recursion."
 
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,337 ⟶ 1,381:
}
r(l + 1)
}</langsyntaxhighlight>
 
Run without arguments on a 64-bit system:
Line 1,455 ⟶ 1,499:
In Gri 2.12.23 the total depth of command calls is limited to an internal array size <code>cmd_being_done_LEN</code> which is 100. There's no protection or error check against exceeding this, so the following code segfaults shortly after 100,
 
<langsyntaxhighlight Grilang="gri">`Recurse'
{
show .depth.
Line 1,462 ⟶ 1,506:
}
.depth. = 1
Recurse</langsyntaxhighlight>
 
=={{header|Groovy}}==
{{Trans|Java}}
Solution:
<langsyntaxhighlight lang="groovy">def recurse;
recurse = {
try {
Line 1,476 ⟶ 1,520:
}
 
recurse(0)</langsyntaxhighlight>
 
{{out}}
Line 1,482 ⟶ 1,526:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Debug.Trace (trace)
 
recurse :: Int -> Int
Line 1,488 ⟶ 1,532:
 
main :: IO ()
main = print $ recurse 1</langsyntaxhighlight>
 
Or point-free:
<langsyntaxhighlight lang="haskell">import Debug.Trace (trace)
import Data.Function (fix)
 
Line 1,498 ⟶ 1,542:
 
main :: IO ()
main = print $ recurse 1</langsyntaxhighlight>
 
 
Or, more practically, testing up to a given depth:
 
<langsyntaxhighlight lang="haskell">import Debug.Trace (trace)
 
testToDepth :: Int -> Int -> Int
Line 1,511 ⟶ 1,555:
 
main :: IO ()
main = print $ testToDepth 1000000 1</langsyntaxhighlight>
{{Out}}
<pre>...
Line 1,530 ⟶ 1,574:
 
=={{header|hexiscript}}==
<langsyntaxhighlight lang="hexiscript">fun rec n
println n
rec (n + 1)
endfun
 
rec 1</langsyntaxhighlight>
 
=={{header|HolyC}}==
The point at which a stack overflow occurs varies depending upon how many parameters passed onto the stack. Running the code from within the editor on a fresh boot of TempleOS will cause a stack overflow when <code>i</code> is larger than ~8100.
 
<langsyntaxhighlight lang="holyc">U0 Recurse(U64 i) {
Print("%d\n", i);
Recurse(i + 1);
}
 
Recurse(0);</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">function test(counter) {
print(counter)
test(counter+1)
Line 1,555 ⟶ 1,599:
software {
test(0)
}</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main()
envar := "MSTKSIZE"
write(&errout,"Program to test recursion depth - dependant on the environment variable ",envar," = ",\getenv(envar)|&null)
Line 1,569 ⟶ 1,613:
write( d +:= 1)
deepdive()
end</langsyntaxhighlight>
Note: The stack size environment variable defaults to about 50000 words. This terminates after approximately 3500 recursions (Windows). The interpreter should terminate with a 301 error, but currently this does not work.
 
=={{header|Inform 7}}==
<langsyntaxhighlight lang="inform7">Home is a room.
 
When play begins: recurse 0.
Line 1,579 ⟶ 1,623:
To recurse (N - number):
say "[N].";
recurse N + 1.</langsyntaxhighlight>
 
Using the interpreters built into Windows build 6F95, a stack overflow occurs after 6529 recursions on the Z-machine or 2030 recursions on Glulx.
Line 1,588 ⟶ 1,632:
Note also that task assumes that all stack frames must be the same size, which is probably not the case.
 
<langsyntaxhighlight Jlang="j">(recur=: verb def 'recur smoutput N=:N+1')N=:0</langsyntaxhighlight>
 
This above gives a stack depth of 9998 on one machine.
Line 1,595 ⟶ 1,639:
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>
public class RecursionTest {
Line 1,610 ⟶ 1,654:
}
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,620 ⟶ 1,664:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
function recurse(depth)
{
Line 1,634 ⟶ 1,678:
 
var maxRecursion = recurse(1);
document.write("Recursion depth on this system is " + maxRecursion);</langsyntaxhighlight>
 
{{out}} (Chrome):
Line 1,651 ⟶ 1,695:
 
'''Arity-0 Function'''
<langsyntaxhighlight lang="jq">def zero_arity:
if (. % 1000000 == 0) then . else empty end, ((.+1)| zero_arity);
 
1|zero_arity</langsyntaxhighlight>
'''Arity-1 Function'''
<langsyntaxhighlight lang="jq">def with_arity(n):
if (n % 1000 == 0) then n else empty end, with_arity(n+1);
 
with_arity(1)</langsyntaxhighlight>
 
'''Results using jq 1.4'''
<syntaxhighlight lang="sh">
<lang sh>
# Arity 0 - without TCO:
...
Line 1,680 ⟶ 1,724:
242000 # 50.0 MB (5h:14m)
# [job cancelled manually after over 5 hours]
</syntaxhighlight>
</lang>
'''Results using jq with TCO'''
 
The arity-0 test was stopped after the recursive function had been called 100,000,000 (10^8) times. The memory required did not grow beyond 360 KB (sic).
<syntaxhighlight lang="sh">
<lang sh>
$ time jq -n -f Find_limit_of_recursions.jq
...
Line 1,693 ⟶ 1,737:
user 2m0.534s
sys 0m0.329s
</syntaxhighlight>
</lang>
 
The arity-1 test process was terminated simply because it had become too slow; at that point it had only consumed about 74.6K MB.
<syntaxhighlight lang="sh">
<lang sh>
...
56000 # 9.9MB
Line 1,710 ⟶ 1,754:
406000 # 74.6 MB (8h:50m)
412000 # 74.6 MB (9h:05m)
# [job cancelled manually after over 9 hours]</langsyntaxhighlight>
'''Discussion'''
 
Line 1,725 ⟶ 1,769:
 
'''Clean'''
<syntaxhighlight lang="julia">
<lang Julia>
function divedivedive(d::Int)
try
Line 1,733 ⟶ 1,777:
end
end
</syntaxhighlight>
</lang>
'''Dirty'''
<syntaxhighlight lang="julia">
<lang Julia>
function divedivedive()
global depth
Line 1,741 ⟶ 1,785:
divedivedive()
end
</syntaxhighlight>
</lang>
'''Main'''
<syntaxhighlight lang="julia">
<lang Julia>
depth = divedivedive(0)
println("A clean dive reaches a depth of ", depth, ".")
Line 1,752 ⟶ 1,796:
end
println("A dirty dive reaches a depth of ", depth, ".")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,764 ⟶ 1,808:
 
One might have expected that the result would be the same (or only vary over a small range) for a given configuration but in fact the results are all over the place - running the program a number of times I obtained figures as high as 26400 and as low as 9099! I have no idea why.
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun recurse(i: Int) {
Line 1,775 ⟶ 1,819:
}
 
fun main(args: Array<String>) = recurse(0)</langsyntaxhighlight>
 
{{out}}
Line 1,784 ⟶ 1,828:
=={{header|Liberty BASIC}}==
Checks for the case of gosub & for proper subroutine.
<syntaxhighlight lang="lb">
<lang lb>
'subroutine recursion limit- end up on 475000
 
Line 1,793 ⟶ 1,837:
call test n+1
end sub
</langsyntaxhighlight>
 
<syntaxhighlight lang="lb">
<lang lb>
'gosub recursion limit- end up on 5767000
[test]
Line 1,801 ⟶ 1,845:
if n mod 1000 = 0 then locate 1,1: print n
gosub [test]
</syntaxhighlight>
</lang>
 
=={{header|LIL}}==
lil.c allows an optional build time value to set a limit on recursion:
<langsyntaxhighlight lang="c">/* Enable limiting recursive calls to lil_parse - this can be used to avoid call stack
* overflows and is also useful when running through an automated fuzzer like AFL */
/*#define LIL_ENABLE_RECLIMIT 10000*/</langsyntaxhighlight>
 
Otherwise, it is a race to run out of stack:
Line 1,828 ⟶ 1,872:
Like Scheme, Logo guarantees tail call elimination, so recursion is effectively unbounded. You can catch a user interrupt though to see how deep you could go.
 
<langsyntaxhighlight lang="logo">make "depth 0
 
to recurse
Line 1,838 ⟶ 1,882:
; hit control-C after waiting a while
print error ; 16 Stopping... recurse [make "depth :depth + 1]
(print [Depth reached:] :depth) ; some arbitrarily large number</langsyntaxhighlight>
 
=={{header|LSL}}==
Line 1,846 ⟶ 1,890:
 
To test it yourself; rez a box on the ground, and add the following as a New Script.
<langsyntaxhighlight LSLlang="lsl">integer iLimit_of_Recursion = 0;
Find_Limit_of_Recursion(integer x) {
llOwnerSay("x="+(string)x);
Line 1,858 ⟶ 1,902:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,875 ⟶ 1,919:
Lua (version 5.3) support proper tail call, if the recursion is proper tail call there is no limit.
Otherwise, it is limited by stack size set by the implementation.
<syntaxhighlight lang="lua">
<lang Lua>
local c = 0
function Tail(proper)
Line 1,891 ⟶ 1,935:
ok,check = pcall(Tail,false)
print(c, ok, check)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,900 ⟶ 1,944:
=={{header|M2000 Interpreter}}==
===Modules & Functions===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module checkit {
Global z
Line 1,949 ⟶ 1,993:
}
Checkit
</syntaxhighlight>
</lang>
In Wine give these:
<pre>
Line 1,969 ⟶ 2,013:
 
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
\\ recursion for subs controled by a value
Line 1,997 ⟶ 2,041:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
The variable $RecursionLimit can be read for its current value or set to different values. eg
<syntaxhighlight lang="text">$RecursionLimit=10^6</langsyntaxhighlight>
Would set the recursion limit to one million.
 
Line 2,008 ⟶ 2,052:
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> get(0,'RecursionLimit')
 
ans =
Line 2,019 ⟶ 2,063:
ans =
 
2500</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">f(p) := f(n: p + 1)$
f(0);
Maxima encountered a Lisp error:
Line 2,030 ⟶ 2,074:
 
n;
406</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">П2 ПП 05 ИП1 С/П
ИП0 ИП2 - x<0 20 ИП0 1 + П0 ПП 05
ИП1 1 + П1 В/О</langsyntaxhighlight>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE recur;
 
IMPORT InOut;
Line 2,051 ⟶ 2,095:
BEGIN
recursion (0)
END recur.</langsyntaxhighlight>
Producing this:
<syntaxhighlight lang="modula-2">
<lang Modula-2>
jan@Beryllium:~/modula/rosetta$ recur >testfile
Segmentation fault
Line 2,061 ⟶ 2,105:
-rw-r--r-- 1 jan users 523264 2011-05-20 00:26 testfile
jan@Beryllium:~/modula/rosetta$ wc testfile
0 1 523264 testfile</langsyntaxhighlight>
So the recursion depth is just over half a million.
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">RECURSE
IF $DATA(DEPTH)=1 SET DEPTH=1+DEPTH
IF $DATA(DEPTH)=0 SET DEPTH=1
WRITE !,DEPTH_" levels down"
DO RECURSE
QUIT</langsyntaxhighlight>
End of the run ...<pre>
1918 levels down
Line 2,083 ⟶ 2,127:
=={{header|Nanoquery}}==
{{trans|Python}}
<langsyntaxhighlight lang="nanoquery">def recurse(counter)
println counter
counter += 1
Line 2,089 ⟶ 2,133:
end
 
recurse(1)</langsyntaxhighlight>
{{out}}
<pre>1
Line 2,101 ⟶ 2,145:
 
=={{header|Neko}}==
<syntaxhighlight lang="actionscript">/**
<lang ActionScript>/**
Recursion limit, in Neko
*/
Line 2,128 ⟶ 2,172:
 
try $print("Recurse: ", recurse(0), " sum: ", sum, "\n")
catch with $print("recurse limit exception: ", counter, " ", with, "\n")</langsyntaxhighlight>
 
{{out}}
Line 2,138 ⟶ 2,182:
=={{header|NetRexx}}==
Like Java, NetRexx memory allocation is managed by the JVM under which it is run. The following sample presents runtime memory allocations then begins the recursion run.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 2,175 ⟶ 2,219:
say
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,188 ⟶ 2,232:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc recurse(i: int): int =
echo i
recurse(i+1)
echo recurse(0)</langsyntaxhighlight>
Compiled without optimizations (debug build), the program stops with the following message:
<pre>Error: call depth limit reached in a debug build (2000 function calls). You can change it with -d:nimCallDepthLimit=<int> but really try to avoid deep recursions instead.</pre>
Line 2,209 ⟶ 2,253:
If the recursion is not a tail one, the execution is stopped with the message
"Stack overflow":
<langsyntaxhighlight lang="ocaml"># let last = ref 0 ;;
val last : int ref = {contents = 0}
# let rec f i =
Line 2,219 ⟶ 2,263:
stack overflow during evaluation (looping recursion?).
# !last ;;
- : int = 262067</langsyntaxhighlight>
 
here we see that the function call stack size is 262067.
 
<langsyntaxhighlight lang="ocaml">(* One can build a function from the idea above, catching the exception *)
 
let rec_limit () =
Line 2,239 ⟶ 2,283:
 
(* Since with have eaten some stack with this function, the result is slightly lower.
But now it may be used inside any function to get the available stack space *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,245 ⟶ 2,289:
Limit found is 173510 on Windows system. Should be more on Linux system.
 
<langsyntaxhighlight Oforthlang="oforth">: limit 1+ dup . limit ;
 
0 limit</langsyntaxhighlight>
 
=={{header|ooRexx}}==
Line 2,273 ⟶ 2,317:
 
Oz supports an unbounded number of tail calls. So the following code can run forever with constant memory use (although the space used to represent <code>Number</code> will slowly increase):
<langsyntaxhighlight lang="oz">declare
proc {Recurse Number}
{Show Number}
Line 2,279 ⟶ 2,323:
end
in
{Recurse 1}</langsyntaxhighlight>
 
With non-tail recursive functions, the number of recursions is only limited by the available memory.
Line 2,285 ⟶ 2,329:
=={{header|PARI/GP}}==
As per "Recursive functions" in the Pari/GP users's manual.
<langsyntaxhighlight lang="parigp">dive(n) = dive(n+1)
dive(0)</langsyntaxhighlight>
 
The limit is the underlying C language stack. Deep recursion is detected before the stack is completely exhausted (by checking <code>RLIMIT_STACK</code>) so a <code>gp</code> level error is thrown instead of a segfault.
Line 2,296 ⟶ 2,340:
Maximum recursion depth is memory dependent.
 
<langsyntaxhighlight lang="perl">my $x = 0;
recurse($x);
 
Line 2,302 ⟶ 2,346:
print ++$x,"\n";
recurse($x);
}</langsyntaxhighlight>
 
 
Line 2,318 ⟶ 2,362:
On 32-bit the limit is an impressive 31 million. I have seen this hit 43 million on 64-bit, but it then forced a hard reboot.<br>
Those limits will obviously be significantly smaller for routines with more parameters, local variables, and temps.
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">atom</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time<span style="color: #0000FF;">(<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">1</span>
Line 2,336 ⟶ 2,380:
<span style="color: #000000;">recurse<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
{{out|output|text=&nbsp; 32 bit}}
<pre>
Line 2,380 ⟶ 2,424:
=== saner ===
The following much more safely merely tests it can reach 20,000,000, plus however far it gets in the last whole-second
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">atom</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time<span style="color: #0000FF;">(<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">1</span>
Line 2,405 ⟶ 2,449:
<span style="color: #000000;">recurse<span style="color: #0000FF;">(<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,416 ⟶ 2,460:
depth: 3725849 (tearing down)
</pre>
 
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Find_limit_of_recursion
by Galileo, 10/2022 #/
 
def sec msec int enddef
 
sec var t
 
def recursion
1 +
sec t 1 + > if t 1 + var t dup print nl endif
recursion
enddef
 
0 recursion</syntaxhighlight>
{{out}}
<pre>281007
431296
581394
730334
879369
1029498
1179530
1330012
1479943
1630421
1781000
1930959
2081595
2231553
2381764
2531888
2682392
2832907
2983242
3133677
3284111
3434178
3584534
3734997
3885133
4035703
4185613
4336355
4486693
4635764
4786107
4935949
5086156
5235687
5385416
5535747
5685633
5835858
5985753
6135743
6285747
6436123
6585421
6735203
6885286
7035236
7185132
7334455
7484643
7618401
7731876
7852957
7976679
8103526
8230876
8358600
8488773
8623796
8763058
8898198
9046186
9189766
9339550
9489755
9633985
9781880
9931149
10080277
10227093
10361576
10498033
10646428
10795650
10940499
11090442
11239675
11389776
11539185
11687704
11831276
11966704
12086836
Your program has run out of memory, one moment please
 
 
 
Global & Local Variables
 
*** Error detected ***
*** Stack content:
[12197563]
*** Location: .. Rosetta Code problem: http://rosettacode.org/wiki/Find_limit_of_recursion by Galileo, 10/2022 #/ def sec msec ..
=== Press any key to exit ===</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
function a() {
static $i = 0;
Line 2,424 ⟶ 2,578:
a();
}
a();</langsyntaxhighlight>
 
{{out}}
Line 2,476 ⟶ 2,630:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
recurs: proc options (main) reorder;
dcl sysprint file;
Line 2,493 ⟶ 2,647:
call recursive();
end recurs;
</syntaxhighlight>
</lang>
 
Result (abbreviated):
Line 2,507 ⟶ 2,661:
 
Obviously, if the procedure '''recursive''' would have contained local variables, the depth of recursion would be reached much earlier...
 
=={{header|PL/M}}==
<syntaxhighlight lang="PL/M">
100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUM: PROCEDURE (N);
DECLARE S (8) BYTE INITIAL ('.....',13,10,'$');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P-1;
C = N MOD 10 + '0';
IF (N := N/10) > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUM;
 
RECURSE: PROCEDURE;
DECLARE CNT ADDRESS INITIAL (1);
 
CALL PRINT$NUM(CNT);
CNT = CNT + 1;
CALL RECURSE;
 
END RECURSE;
 
CALL RECURSE;
CALL EXIT;
 
EOF
</syntaxhighlight>
 
=={{header|PowerShell}}==
Line 2,518 ⟶ 2,704:
we send the results to a pipeline, we can process the earlier results before handling the
exception.
<syntaxhighlight lang="powershell">
<lang PowerShell>
function TestDepth ( $N )
{
Line 2,534 ⟶ 2,720:
}
"Last level before error: " + $Depth
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,547 ⟶ 2,733:
 
In addition to the stack size the recursion limit for procedures is further limited by the procedure's parameters and local variables which are also stored on the same stack.
<langsyntaxhighlight PureBasiclang="purebasic">Procedure Recur(n)
PrintN(str(n))
Recur(n+1)
EndProcedure
 
Recur(1)</langsyntaxhighlight>
Stack overflow after 86317 recursions on x86 Vista.
 
===Classic===
<syntaxhighlight lang="purebasic">rec:
<lang PureBasic>rec:
PrintN(str(n))
n+1
Gosub rec
Return</langsyntaxhighlight>
Stack overflow after 258931 recursions on x86 Vista.
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import sys
print(sys.getrecursionlimit())</langsyntaxhighlight>
 
To set it:
 
<langsyntaxhighlight lang="python">import sys
sys.setrecursionlimit(12345)</langsyntaxhighlight>
 
Or, we can test it:
 
<langsyntaxhighlight lang="python">def recurse(counter):
print(counter)
counter += 1
recurse(counter)</langsyntaxhighlight>
 
Giving:
 
<langsyntaxhighlight lang="python">File "<stdin>", line 2, in recurse
RecursionError: maximum recursion depth exceeded while calling a Python object
996</langsyntaxhighlight>
 
Which we could change if we wanted to.
Line 2,589 ⟶ 2,775:
We can catch the RecursionError and keep going a bit further:
 
<langsyntaxhighlight lang="python">def recurseDeeper(counter):
try:
print(counter)
Line 2,595 ⟶ 2,781:
except RecursionError:
print("RecursionError at depth", counter)
recurseDeeper(counter + 1)</langsyntaxhighlight>
 
Giving:
 
<langsyntaxhighlight lang="python">1045
Fatal Python error: Cannot recover from stack overflow.</langsyntaxhighlight>
 
 
Line 2,606 ⟶ 2,792:
 
When the direct approach
<langsyntaxhighlight Quackerylang="quackery">0 [ 1+ dup echo cr recurse ]</langsyntaxhighlight>
was still churning out digits after 13,000,000 (Quackery does not optimise tail end recursion) I decided on an indirect approach, by asking the equivalent question, "What is the largest nest that Quackery can create?" as each item on the Quackery return stack occupies two items in a nest (i.e. dynamic array).
<langsyntaxhighlight Quackerylang="quackery">' [ 1 ] [ dup size echo cr dup join again ]</langsyntaxhighlight>
On the first trial the process died with a segmentation error after reaching 2^30 items, and on the second trial the computer became very unresponsive at the same point, but made it to 2^31 items before I force-quit it.
 
Line 2,619 ⟶ 2,805:
=={{header|R}}==
R's recursion is counted by the number of expressions to be evaluated, rather than the number of function calls.
<langsyntaxhighlight lang="r">#Get the limit
options("expressions")
 
Line 2,632 ⟶ 2,818:
 
}
recurse(0)</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
(define (recursion-limit)
(with-handlers ((exn? (lambda (x) 0)))
(add1 (recursion-limit))))</langsyntaxhighlight>
 
This should theoretically return the recursion limit, as the function can't be tail-optimized and there's an exception handler to return a number when an error is encountered. For this to work one has to give the Racket VM the maximum possible memory limit and wait.
Line 2,646 ⟶ 2,832:
Maximum recursion depth is memory dependent. Values in excess of 1 million are easily achieved.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>my $x = 0;
recurse;
 
Line 2,653 ⟶ 2,839:
say $x if $x %% 1_000_000;
recurse;
}</langsyntaxhighlight>
 
{{out}}
Line 2,675 ⟶ 2,861:
When run, this will display the address stack depth until it reaches the max depth. Once the address stack is full, Retro will crash.
 
<langsyntaxhighlight Retrolang="retro">: try -6 5 out wait 5 in putn cr try ;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 2,684 ⟶ 2,870:
This limit was maybe changed later to allow the user to specify the limit. &nbsp; My memory is really fuzzy
<br>about these details, it was over thirty years ago.
<langsyntaxhighlight lang="rexx">/*REXX program finds the recursion limit: a subroutine that repeatably calls itself. */
parse version x; say x; say /*display which REXX is being used. */
#=0 /*initialize the numbers of invokes to 0*/
Line 2,694 ⟶ 2,880:
#=#+1 /*bump number of times SELF is invoked. */
say # /*display the number of invocations. */
call self /*invoke ourselves recursively. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using Regina 3.6 under Windows/XP Pro:}}
<pre>
Line 2,768 ⟶ 2,954:
===recursive subroutine===
All REXXes were executed under Windows/XP Pro.
<langsyntaxhighlight lang="rexx">/*REXX program finds the recursion limit: a subroutine that repeatably calls itself. */
parse version x; say x; say /*display which REXX is being used. */
#=0 /*initialize the numbers of invokes to 0*/
Line 2,777 ⟶ 2,963:
self: #=#+1 /*bump number of times SELF is invoked. */
say # /*display the number of invocations. */
call self /*invoke ourselves recursively. */</langsyntaxhighlight>
{{out|output|text=&nbsp; (paraphrased and edited)}}
<pre>
Line 2,801 ⟶ 2,987:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
recurse(0)
 
Line 2,807 ⟶ 2,993:
see ""+ x + nl
recurse(x+1)
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
« 1 + <span style="color:blue">RECUR</span> » '<span style="color:blue">RECUR</span>' STO
 
0 <span style="color:blue">RECUR</span>
Each recursive call will increase the return stack size by 5 nibbles, which means that on a basic 32-kilobyte calculator, there's room for over 10,000 recursive calls of the above type. If the recursion algorithm needs to pass arguments through the data stack or use local variables, the number of recursions will be much lower.
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def recurse x
puts x
recurse(x+1)
end
 
recurse(0)</langsyntaxhighlight>
{{out}} Produces a SystemStackError:
<pre>
Line 2,829 ⟶ 3,021:
when tracking Stack overflow exceptions ; returns 8732 on my computer :
 
<langsyntaxhighlight lang="ruby">def recurse n
recurse(n+1)
rescue SystemStackError
Line 2,835 ⟶ 3,027:
end
 
puts recurse(0)</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">a = recurTest(1)
function recurTest(n)
Line 2,845 ⟶ 3,037:
n = recurTest(n+1)
[ext]
end function</langsyntaxhighlight>
<pre>327000</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn recurse(n: i32) {
println!("depth: {}", n);
recurse(n + 1)
Line 2,856 ⟶ 3,048:
fn main() {
recurse(0);
}</langsyntaxhighlight>
 
{{out}}
Line 2,870 ⟶ 3,062:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
attr r:INT;
recurse is
Line 2,881 ⟶ 3,073:
recurse;
end;
end;</langsyntaxhighlight>
 
Segmentation fault is reached when r is 130560.
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def recurseTest(i:Int):Unit={
try{
recurseTest(i+1)
Line 2,893 ⟶ 3,085:
}
}
recurseTest(0)</langsyntaxhighlight>
{{out}} depending on the current stack size:
<pre>Recursion depth on this system is 4869.</pre>
If your function is tail-recursive the compiler transforms it into a loop.
<langsyntaxhighlight lang="scala">def recurseTailRec(i:Int):Unit={
if(i%100000==0) println("Recursion depth is " + i + ".")
recurseTailRec(i+1)
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (recurse number)
(begin (display number) (newline) (recurse (+ number 1))))
 
(recurse 1)</langsyntaxhighlight>
Implementations of Scheme are required to support an unbounded number of tail calls. Furthermore, implementations are encouraged, but not required, to support exact integers of practically unlimited size.
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">put recurse(1)
 
function recurse n
put n
get the recurse of (n+1)
end recurse</langsyntaxhighlight>
Recursion limit error is reached at 40.
 
=={{header|Sidef}}==
Maximum recursion depth is memory dependent.
<langsyntaxhighlight lang="ruby">func recurse(n) {
say n;
recurse(n+1);
}
 
recurse(0);</langsyntaxhighlight>
{{out}}
<pre>
Line 2,942 ⟶ 3,134:
In the Squeak dialect of Smalltalk:
 
<langsyntaxhighlight lang="smalltalk">
Object subclass: #RecursionTest
instanceVariableNames: ''
Line 2,948 ⟶ 3,140:
poolDictionaries: ''
category: 'RosettaCode'
</syntaxhighlight>
</lang>
 
Add the following method:
 
<langsyntaxhighlight lang="smalltalk">
counter: aNumber
^self counter: aNumber + 1
</syntaxhighlight>
</lang>
 
Call from the Workspace:
 
<langsyntaxhighlight lang="smalltalk">
r := RecursionTest new.
r counter: 1.
</syntaxhighlight>
</lang>
 
After some time the following error pops up:
Line 2,977 ⟶ 3,169:
 
Other dialects raise an exception:
<langsyntaxhighlight lang="smalltalk">
counter := 0.
down := [ counter := counter + 1. down value ].
down on: RecursionError do:[
'depth is ' print. counter printNL
].</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun recLimit () =
1 + recLimit ()
handle _ => 0
 
val () = print (Int.toString (recLimit ()) ^ "\n")</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">var n = 1
 
func recurse() {
Line 3,000 ⟶ 3,192:
}
 
recurse()</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc recur i {
puts "This is depth [incr i]"
catch {recur $i}; # Trap error from going too deep
}
recur 0</langsyntaxhighlight>
The tail of the execution trace looks like this:
<pre>
Line 3,017 ⟶ 3,209:
</pre>
Note that the maximum recursion depth is a tunable parameter, as is shown in this program:
<langsyntaxhighlight lang="tcl"># Increase the maximum depth
interp recursionlimit {} 1000000
proc recur i {
Line 3,025 ⟶ 3,217:
}
}
recur 0</langsyntaxhighlight>
For Tcl 8.5 on this platform, this prints:
<pre>
Line 3,036 ⟶ 3,228:
 
=={{header|TSE SAL}}==
<syntaxhighlight lang="tse sal">
<lang TSE SAL>
// library: program: run: recursion: limit <description>will stop at 3616</description> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=runprrli.s) [kn, ri, su, 25-12-2011 23:12:02]
PROC PROCProgramRunRecursionLimit( INTEGER I )
Line 3,046 ⟶ 3,238:
PROCProgramRunRecursionLimit( 1 )
END
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
 
<langsyntaxhighlight lang="txrlisp">(set-sig-handler sig-segv
(lambda (signal async-p) (throw 'out)))
 
Line 3,060 ⟶ 3,252:
 
(catch (recurse)
(out () (put-line `caught segfault!\nreached depth: @{*count*}`)))</langsyntaxhighlight>
 
{{out}}
Line 3,071 ⟶ 3,263:
{{works with|Bourne Again SHell}}
 
<langsyntaxhighlight lang="bash">recurse()
{
# since the example runs slowly, the following
Line 3,085 ⟶ 3,277:
}
 
recurse 0</langsyntaxhighlight>
 
The Bash reference manual says <cite>No limit is placed on the number of recursive calls</cite>, nonetheless a segmentation fault occurs at 13777 (Bash v3.2.19 on 32bit GNU/Linux)
 
=={{header|Ursa}}==
<langsyntaxhighlight lang="ursa">def recurse (int counter)
try
recurse (+ counter 1)
Line 3,098 ⟶ 3,290:
end
 
recurse 1</langsyntaxhighlight>
 
=={{header|Uxntal}}==
Uxn has a known stack size of 256 bytes, which allows 128 function calls. However, assuming we don’t know this, we can find the stack size with a program anyway. In older versions of Uxn, it was possible to detect stack overflow with the System vector, which would make this task easier, but the current Uxn stacks are circular, with no overflow and underflow checks, which means that we have to get a bit more creative. Calling a recursive function enough times will cause the return stack pointer to wrap around and overwrite the first return address, which means execution will be trapped in the recursive function forever. By detecting when the function has run more times than expected, the recursion limit can be found.
 
<syntaxhighlight lang="Uxntal">|00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1
|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1
 
|00 @calls $1
 
|0100
#01
&loop
DUP .calls STZ
recurse
INC !&loop
 
@recurse
( keep calling recurse until stack value is 00 )
#01 SUB DUP #00 EQU ?&done
 
recurse
 
( as we walk back up the stack, increment counter )
&done INC
 
( if we go above the original call count, the stack was corrupted )
DUP .calls LDZ GTH ?&fail
JMP2r
 
&fail
;msg1 print-str
.calls LDZ print-hex
;msg2 print-str
#80 .System/state DEO BRK
 
@print-str
&loop
LDAk .Console/write DEO
INC2 LDAk ?&loop
POP2
JMP2r
 
@print-hex
DUP #04 SFT print-digit #0f AND print-digit
JMP2r
 
@print-digit
DUP #09 GTH #27 MUL ADD #30 ADD .Console/write DEO
JMP2r
 
@msg1 "Stack 20 "overflow 20 "at 20 "# 00
@msg2 20 "calls. 0a00</syntaxhighlight>
 
=={{header|Vala}}==
<langsyntaxhighlight Valalang="vala">void recur(uint64 v ) {
print (@"$v\n");
recur( v + 1);
Line 3,108 ⟶ 3,352:
void main() {
recur(0);
}</langsyntaxhighlight>
{{out}}
trimmed output
Line 3,122 ⟶ 3,366:
=={{header|VBA}}==
 
<syntaxhighlight lang="vb">
<lang vb>
Option Explicit
 
Line 3,136 ⟶ 3,380:
Limite_Recursivite = Cpt 'return
End Function
</syntaxhighlight>
</lang>
{{out}}
<pre>The limit is : 6442</pre>
Line 3,143 ⟶ 3,387:
Haven't figured out how to see the depth. And this depth is that of calling the O/S rather than calling within.
 
<langsyntaxhighlight lang="vb">'mung.vbs
option explicit
 
Line 3,155 ⟶ 3,399:
wscript.echo "[Depth",c & "] Mung until no good."
CreateObject("WScript.Shell").Run "cscript Mung.vbs " & c, 1, true
wscript.echo "[Depth",c & "] no good."</langsyntaxhighlight>
 
Okay, the internal limits version.
 
<langsyntaxhighlight lang="vb">'mung.vbs
option explicit
 
Line 3,172 ⟶ 3,416:
end sub
 
mung 0</langsyntaxhighlight>
 
{{out}} (abbrev.):
Line 3,184 ⟶ 3,428:
[Level 1719] no good</pre>
 
=={{header|V (Vlang)}}==
It'll be some number, depending on machine and environment.
<langsyntaxhighlight lang="go">// Find limit of recursion, in V (Vlang)
module main
 
Line 3,197 ⟶ 3,441:
println(n)
recurse(n+1)
}</langsyntaxhighlight>
{{out}}
<pre>prompt$ v run find-limit-of-recursion.v
Line 3,205 ⟶ 3,449:
prompt$ echo $?
11</pre>
 
=={{header|Wren}}==
I cannot find any published information on the maximum amount of memory that can be used by a fiber's stack - and hence the limit of recursion for a given function - but it appears to be 4 GB on a sufficiently large 64-bit system such as my own (32 GB) with no shell limit.
 
The final figure produced by the following script was 536,870,500 and multiplying by 8 (the number of bytes of storage required for the parameter 'n') gives 4,294,964,000 which is just 3,296 bytes short of 4 GB.
 
In Wren a fiber's stack starts small and is increased as required. It appears that the runtime makes no attempt to check for any limitation internally leaving the script to eventually segfault.
<syntaxhighlight lang="wren">var F = Fn.new { |n|
if (n%500 == 0) System.print(n) // print progress after every 500 calls
F.call(n + 1)
}
F.call(1)</syntaxhighlight>
 
{{out}}
<pre>
...
536870000
536870500
Segmentation fault (core dumped)
</pre>
 
=={{header|x86 Assembly}}==
Line 3,210 ⟶ 3,474:
{{works with|nasm}}
 
<langsyntaxhighlight lang="asm"> global main
 
section .text
Line 3,222 ⟶ 3,486:
add eax, 1
call recurse
ret</langsyntaxhighlight>
 
I've used gdb and the command <tt>print $eax</tt> to know when the segmentation fault occurred. The result was 2094783.
 
=={{header|WrenXPL0}}==
On the Raspberry Pi this causes a Segmentation fault at the recursion
I cannot find any published information on the maximum amount of memory that can be used by a fiber's stack - and hence the limit of recursion for a given function - but it appears to be 4 GB on a sufficiently large 64-bit system such as my own (32 GB) with no shell limit.
levels shown in Output.
 
The stack size is about 8 MB. The original compiler pushes a single
The final figure produced by the following script was 536,870,500 and multiplying by 8 (the number of bytes of storage required for the parameter 'n') gives 4,294,964,000 which is just 3,296 bytes short of 4 GB.
4-byte value (the return address for Recurse) onto the stack.
 
The optimizing compiler pushes an additional 4-byte value (r11), which is
In Wren a fiber's stack starts small and is increased as required. It appears that the runtime makes no attempt to check for any limitation internally leaving the script to eventually segfault.
the base address of variables local to Recurse. But since there aren't
<lang ecmascript>var f
any local variables in this situation, the optimizing compiler isn't as
f = Fn.new { |n|
optimal as it could be.
if (n%500 == 0) System.print(n) // print progress after every 500 calls
System.write("") // required to fix a VM recursion bug
f.call(n + 1)
}
f.call(1)</lang>
 
The MS-DOS version crashes at 12,224 levels. The allocated stack size is
16,384 bytes. But since each call pushes a 4-byte value, the actual limit
should be a maximum of 4,096.
 
<syntaxhighlight lang "XPL0">int Lev;
proc Recurse;
[if (Lev & $3FF) = 0 then
[IntOut(0, Lev); ChOut(0, ^ )];
Lev:= Lev+1;
Recurse;
];
 
[Lev:= 0;
Recurse;
]</syntaxhighlight>
{{out}}
<pre>
2,096,128 for the original compiler (xplr)
...
1,047,552 for the optimizing compiler (xpl0)
536870000
536870500
Segmentation fault (core dumped)
</pre>
 
Line 3,255 ⟶ 3,530:
(For a more realistic example see this task's entry for 8080 Assembly.)
 
<langsyntaxhighlight lang="z80">org &0000
LD SP,&FFFF ;3 bytes
loop:
Line 3,267 ⟶ 3,542:
jr * ;2 bytes
;address &0024 begins here
word 0 ;placeholder for stack pointer</langsyntaxhighlight>
 
This is the minimum amount of code I can come up with that can check for the limit. (Note that this code has no way to display the results of the test to the user, so on real hardware the limit of recursion is much less, but for an emulator this will suffice.) The concept here is relatively simple. Do the following in a loop:
Line 3,276 ⟶ 3,551:
* The <code>CP</code> instruction only compares the accumulator to an 8 bit register, so to compare HL to BC we actually have to subtract them. If the result is zero, they were the same to begin with.
* If they're different, then the act of pushing AF clobbered the stack pointer we backed up in step 1. This means recursion is at its limit, so quit looping and halt the CPU.
 
=={{header|Zig}}==
{{Trans|C}}
 
'''Works with:''' 0.11.x, 0.12.0-dev.1381+61861ef39
 
For 0.10.x, replace @call(.some_call_modifier, ...) with @call(.{ .modifier = .some_call_modifier }, ...) in these examples.
 
===Leave TRE to the compiler===
In this version, Zig compiler is free to (not) optimize recursive function, so behaviour may change from one optimization mode to another, like it was with 2-nd example from C section.
<syntaxhighlight lang="zig">const std = @import("std");
 
fn recurse(i: c_uint) void {
std.debug.print("{d}\n", .{i});
// We use wrapping addition operator here to mirror C behaviour.
recurse(i +% 1);
// Line above is equivalent to:
// @call(.auto, recurse, .{i +% 1});
}
 
pub fn main() void {
recurse(0);
return;
}</syntaxhighlight>
 
===Force-disable TRE===
To force-disable "simple tail recursion elimination" (STRE) for all optimize modes, we can use "never_tail" field of enum "std.builtin.CallModifier". It works not as hint, but as a hard requirement, so if it's impossible to fulfill, compile error is outputted.
<syntaxhighlight lang="zig">const std = @import("std");
 
fn recurse(i: c_uint) void {
std.debug.print("{d}\n", .{i});
// We use wrapping addition operator here to mirror C behaviour.
@call(.never_tail, recurse, .{i +% 1});
}
 
pub fn main() void {
recurse(0);
return;
}</syntaxhighlight>
 
Segmentation fault occurs at different values of "i", depending on running platform, but on my platform (with stack size reported by ulimit as 16384) both C and Zig versions (compiled without optimizations output last value in approximately [523500, 524000] range.
 
gcc compiler with -O2 flag eliminated tail recursion, as mentioned in 2-nd example from C section, but in this Zig example recurse function is never turned into loop, even when enabling different optimization modes — we explicitly prohibited compiler from doing it in any optimize/build mode!
 
===Force-enable TRE===
Similarly, we can force-enable mentioned optimization in all optimize modes by using enum field "always_tail". It's (again) a hard requirement and will emit compile error if this requirement is impossible to complete.
<syntaxhighlight lang="zig">const std = @import("std");
 
fn recurse(i: c_uint) void {
std.debug.print("{d}\n", .{i});
// We use wrapping addition operator here to mirror C behaviour.
@call(.always_tail, recurse, .{i +% 1});
}
 
pub fn main() void {
recurse(0);
return;
}</syntaxhighlight>
 
On my machine, segmentation fault never occurs, instead resulting in infinite loop in all optimize modes (as intended).
 
=={{header|zkl}}==
<syntaxhighlight lang ="zkl">fcn{self.fcn()}()</langsyntaxhighlight>
{{out}}
<pre>
1,150

edits