Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Perl so afraid of "deep recursion"?

I recently stumbled across the book Higher-order Perl, which basically suggests ways to do things in Perl in a functional way. The author explains that Perl has 6 out of 7 core features of Lisp, while C has none.

I had a problem which looked like a good candidate for a recursive solution, and I coded it in this fashion. But Perl complained about "deep recursion". I googled a bit and found a Perl monk explaining that "Perl is not Haskell". Apperently you get a complaint by default, when the recursion depth exceeds 100 levels.

There are ways to extend this limit or to turn it off entirely, but my question is:

  • Is there a reason that Perl is so uptight about recursion, while Haskell is not at all?
like image 204
Martin Drautzburg Avatar asked Dec 20 '13 19:12

Martin Drautzburg


People also ask

Does Perl support recursion?

Perl provides us with the flexibility to use subroutines both iteratively and recursively.

How deep can recursion go?

The maximum recursion depth in C depends on a lot of factors, of course. On a typical 64-bit Linux system the default stack size is 8 MB, and the stack alignment is 16 bytes, so you get a recursion depth of about 512K for simple functions.

How can recursion depth be reduced?

Conclusion. The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.


1 Answers

Because in Haskell, we have laziness & guarded recursion and tail call optimization and Perl has neither.

This essentially means that every function call allocates a set amount of memory called "the stack" until the function returns. When you write recursive code, you build up a huge amount of memory because of these nested function calls and eventually can stack overflow. TCO allows the unused chunks to be optimized away.

Without this it's not really a good idea to rely on recursion. For example, say you wrote a recursive version of map, it'd crash with any decent sized list. In Haskell, guarded recursion means that with large lists, the recursive solution is much faster than a "loop" like function.

TLDR: Haskell's implementations are designed to handle a functional/recursive style and perl's implementation is not and back in the good old days, 100 levels of function calls was a sane limit.

like image 189
Daniel Gratzer Avatar answered Sep 28 '22 20:09

Daniel Gratzer