Infinite Recursion

September 2, 2009

A few days ago I posted an article on Tail Call Optimization. One really quick way to determine if any language/VM/interpreter performs Tail Call Optimization (TCO) is to write a function that calls itself, in other words, creating an infinitely recursive function. If the function just runs forever and doesn't return, the interpreter is doing TCO, otherwise you will get some sort of stack overflow error. So I decided to test a variety of languages to see what happens when you write an infinitely recursive function. First up is ruby:

def forever
  forever
end

forever

It was no surprise to me that running this results in this error:

run.rb:2:in `forever': stack level too deep (SystemStackError)
    from run.rb:2:in `forever'
    from run.rb:5

Ruby doesn't have TCO, I knew that. Next up, Python:

def forever(): forever()

forever()

This has a similar result, but the stack track is a little more revealing:

Traceback (most recent call last):
  File "run.py", line 3, in <module>
    forever()
  File "run.py", line 1, in forever
    def forever(): forever()
  File "run.py", line 1, in forever
    def forever(): forever()
...
  File "run.py", line 1, in forever
    def forever(): forever()
  File "run.py", line 1, in forever
    def forever(): forever()
RuntimeError: maximum recursion depth exceeded

This shows pretty clearly what is going on, the stack frames are pilling up and eventually it gets to the point where the Python interpreter says enough is enough. Interestingly enough, this mailing list thread shows that it's completely feasible to add TCO to Python and Guido just doesn't want to add it.

JavaScript is no surprise either, but we can write our infinitely recursive function with an interesting little twist:

(function(){ arguments.callee() })()

Yes that's right, it's an anonymous recursive function! Running this with SpiderMonkey results in InternalError: too much recursion. So how about Java:

class Run {
  public static void main(String[] args) {
    Run run = new Run();
    run.forever();
  }

  public void forever() {
    forever();
  }
} 

The stack trace for this one looks a bit like the Python one, we see a stack frame for each iteration:

Exception in thread "main" java.lang.StackOverflowError
    at Run.forever(Run.java:8)
    at Run.forever(Run.java:8)
    at Run.forever(Run.java:8)
    at Run.forever(Run.java:8)
...

So that means no TCO on the JVM. So Scala doesn't have TCO, right?

def forever : Unit = forever

forever

Wrong. This one runs forever. Scala does TCO with some bytecode tricks which Nick Wiedenbrueck explains really well in this blog post.

Clojure is a functional Lisp saddled with the problem of no-TCO on the JVM, but it gets around it in a slightly different way than Scala. If you write a tail recursive function like this:

(defn forever [] (forever))

You will get a java.lang.StackOverflowError just as you do in Java. Instead, Clojure provides a language level feature to do recursion:

(defn forever [] (recur))

Calling recur in the function makes it call the function again. recur also checks that it is in the tail recursive position, which ends up being an interesting feature because you have to explicitly say "I expect this to do TCO". In other languages that do it transparently, you might think TCO is happening, but it might not be and you won't find out until you get a stack overflow error. Also, this construct allows us to have recursive anonymous functions:

((fn [] (recur)))

Erlang, being a function language, has TCO as well:

-module(run).

-compile(export_all).

forever() ->
  forever().

Now one thing all of these functional languages that have TCO; Scala, Clojure and Erlang, all have in common is that while the infinitely recursive function runs, it essentially does nothing, but it will peg your CPU utilization to nearly 100%. This next language, Haskell, being the mother of all functional langauges, of course has TCO. Here's the function:

forever = forever

Yes, that's a function. And if you call it with forever, it just sits there and runs forever. But here's the crazy thing, it uses no CPU. My guess is that it has to do with lazy evaluation, but I'm not sure. Any ideas?

Posted in Technology | Tags TCO, Haskell, Erlang, Clojure, Python, Javascript, FunctionalProgramming, Ruby, TailCallOptimization, Scala, Java

Comments Comments Feed

1. Just some minor nitpicks: it is true that the Ruby *Language* Specification doesn't enforce TCO, but it also doesn't *forbid* it. YARV, for example, has TCO, it's just not enabled by default. The same applies to Python: the Language Specification doesn't have TCO, but AFAIK PyPy *does* have TCO. Haskell has lazy evaluation and call-by-need semantics. Since you aren't doing anything with your forever function, it will never get evaluated. You have to enforce strict evaluation, by e.g. printing it out. (The same mistake is done on the Computer Language Benchmark Game. There's an Array sorting benchmark where Haskell just blows away even hand-optimized C. The secret is that the benchmark never prints out the contents of the sorted array. The C compiler isn't smart enough to recognize that the array is never actually used anywhere, but Haskell is, and so the entire benchmark basically compiles down to the equivalent of "int main() { return 0; }".)

# Posted By Jörg W Mittag on Wednesday, September 2 2009 at 3:31 PM

2. @Jörg W Mittag - TCO is a language feature, not an implementation optimization. If recursive code might overflow the stack and it might not, then code can't depend on it, and recursion is best used quite sparingly.

# Posted By Peter Burns on Thursday, September 3 2009 at 7:39 PM

3. The Parrot VM also supports explicit tailcalls, so any language written on it can (theoretically) take advantage of them.

$ cat tc.pir
.sub main :main
.tailcall 'main' ()
.end
$ parrot tc.pir #runs forever



# Posted By Christoph Otto on Thursday, September 3 2009 at 10:02 PM

4. TCO isn't just about self-calling. I think the following is expected to run forever in scheme (forgive my poor scheme) but has no equivalent in Clojure, hence Clojure doesn't really have TCO (which it freely admits).

(define (foo) (bar))
(define (bar) (foo))
(foo)

# Posted By Dave on Thursday, September 3 2009 at 10:56 PM

5. Tail call in Scala is a bit similar to the Clojure one, as described by Dave. The JVM has none, so it has to be emulated. As described in Oderskys book "Programming In Scala", Chap 8.9 Tail recursion, at the end it describes the limits: Scala too only tail calls if the calling function calls itself.
(And I'm rather angry about that. The request for tail call recursion in JVMs is in the request list for many years now.)

I'm very impressed by your Haskell findings. I knew these guys are cool, but THAT cool?

# Posted By Falko on Friday, September 4 2009 at 4:20 AM

6. You forgot about F#. It has TCO as well.

# Posted By Vitaliy on Friday, September 4 2009 at 8:10 AM

7. See http://www.lua.org/pil/6.3.html

# Posted By Jasper Van der Jeugt on Friday, September 4 2009 at 9:07 AM

8. @Dave

Clojure supports mutual recursion via another function called trampoline. This will overflow:

(declare bar)

(defn foo [n]
(if (pos? n)
(bar (dec n))
:done-foo))

(defn bar [n]
(if (pos? n)
(foo (dec n))
:done-bar))

(foo 1000000)
-> java.lang.StackOverflowError

To convert to a trampoline, simply return closures over your tail
calls, rather than direct calls. This is as simple as prepending #

(declare bar)

(defn foo [n]
(if (pos? n)
#(bar (dec n))
:done-foo))

(defn bar [n]
(if (pos? n)
#(foo (dec n))
:done-bar))

Then make the top-level call via trampoline:
(trampoline foo 1000000)
-> :done-foo

# Posted By Paul Barry on Tuesday, September 8 2009 at 10:24 AM

9. @Jörg W Mittag

But shouldn't calling the forever function from ghci force evaluation, since ghci needs to print the result?

# Posted By Paul Barry on Tuesday, September 8 2009 at 10:26 AM

10. How can I have my TCO cut in half? Do you have other hints?

# Posted By sugarbaby on Thursday, November 5 2009 at 2:09 AM

11. brian atwood maniac pumps the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. These Brian Atwood 'Loca' studded pumps are so ravishing, that I'd totally be willing to pop an aspirin before wearing them. And I really lovebrian atwood mesh sandals and Brian Atwood Asymmetric Patent Pumps.brian atwood nude patent leather katie lee pumps. Bold shoes like these sculptural purple suede Brian Atwood 'Lola' pumps make an outfit. purple suede Brian Atwood 'Lola' pumpswith a heel that measures approximately 140mm / 5.5 inches with a 30mm / 1 inch concealed platform. Brian Atwood pumps have a closed toe, cutout detail at arch with elasticated straps and a leather sole.
Herve Leger Dress shop specialises in superior Herve Leger Dress, provides hundreds of discount and fashion Herve Leger Dress, sexy Herve Leger Dress, Herve Leger Skirt, disount Herve Leger Dress-a professional Herve Leger Shop.

# Posted By Brian Atwood maniac pumps on Saturday, August 28 2010 at 3:16 AM

12. Wonderful brian atwood shoes for your style.BRIAN ATWOOD High-heeled sandals Purple is in stock in our store only one size in 36.5 EU. Elegant purple color, you will like it.
And these Pink Brian Atwood Maniac Patent Platform Pumps not only romantic and gorgeous too! It's patent leather leave us sunshine warmness and sexy!
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
I really love brian atwood nico patent pump.
And this year, brian atwood maniac pumps are so hot among stars, I saw many times that Victoria-Beckham wearing them on the show time.
If you don’t know about brian atwood…You should. When everyone else is obsessing over the latest pair of Loubs or YS’L’s it’s very easy to overlook awesome shoe lines and designers who push the envelope. brian atwood is one of those designers.I’m a fan of his lines because Atwood really sets out to make his shoes a conversation piece. The use of alternative textures and fabrics makes brian atwood shoes unique. When wearing his shoes you are guaranteed a compliment from someone and a definate shoe in for best footwear. So ladies (and gents) get into these! And I know my card carrying “Shoe Wh*res” are going to love these!
Buy brian atwood shoes at http://www.brianatwoodcom.com. Buy brian atwood pumps at http://www.brianatwoodcom.com/brian-atwood-brian-atwood-pumps-c-65_67.html.
When I original saw these brian atwood loca studded pumps in a metallic version, a while ago, I likeable them OK, but now I am going unhinged for the lavender version!
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood lexia is worth the investment.
Back by popular demand... brian atwood maniac tan, the perfect wear-with-everything color. These wardrobe staples have 5" stiletto heels and hidden 1 1/2" seamless platforms. In a beautiful, very neutral nude tan.
brian atwood whip snake shoe with Exotic whipsnake hidden platform and back metal inset.
Take a walk on the wild side with Atwood Jagger printed knee-high boots. Style them knee high to add sass to an LBD or wear them with the fold-over flap turned up to work this season's hot over-the-knee trend.
brian atwood cage peep Price: $228. 140mm Covered heel. Rounded peep toe. 40mm covered platform. Interwoven cut outs around front. Ankle strap with adjustable metal buckle. Leather insole and lining. Leather sole. Made in Italy.
When it comes to intricate detailing and superb craftsmanship, you know a pair of brian atwood crystal court shoe is worth the investment.
Brian Atwood Platform Chain Pumps with A silver chain scales the lace-up back of this vamped-up pumps.
brian atwood snakeskin platforms is the classic and the elastic heel detail was used again from last Fall.
brian atwood patent leather and mesh Futuristic patent leather style with mesh details and contrast stitching.
Heel measures approximately 95mm/ 3.5 inches. Let your feet do the talking in brian atwood dorota shoes. Wear this chic style with off-duty denim or to liven up office looks.

# Posted By Brian Atwood loca studded pumps on Saturday, August 28 2010 at 3:17 AM

13. A grand wedding on the beach may be the common dream of most single girls. The bright sunshine, the blue sky and the open sea can satisfy all the demands of the romantic girls. Of course, everything will be perfect with a beach wedding dresses.
Every woman deserve the most beautiful wedding dresses at her special day!The most beautiful smile in the word is belong to the brides when she find her wedding dresses!Love is the time when you slows down in front of the shops selling wedding dresses.
Make the day of your engagement a special one with a A-line or princess wedding dresses!Step like a goddess in tea- length ball gowns,formal ball gowns,victorian ball gowns,debutante ball gowns,prom ball gowns, contemporary ball gownsand vintage ball gowns available in chiffon, organza, silk and satin only at weddingdressesnow.com.
Congratulations! Your little daughter is getting married! But being the mother of the bride (or MOB) is not an easy role. Once upon a time mothers of the bride did most of the wedding planning, and thus got to have their own dreams realized. First of all, choose one from the perfect mother of the bride dresses for yourself here and to be the most elegant mother of bride!
Flower girl dresses must be the perfect accessory for the bride's dress. The flower girls look like the bells ring in the wedding announcements as they toll down the aisle one by one or hand in hand. If you are having flower girls at your wedding, take a look at these beautiful selection of Flower girl dresses from http://www.weddingdressesin.com.

# Posted By A line wedding dresses on Saturday, August 28 2010 at 3:17 AM

14.
This is a very good article, it is worth reading.
href="http://www.macmakeupwholesale.com">mac makeup wholesale
Cosmetics
href="http://www.macmakeupwholesale.com">mac cosmetics wholesale
Nars Make up

Discount Make up : - Eyes Lips Face Multi Purpose Brushes
href="http://www.macmakeupwholesale.com">wholesale mac cosmetics
, cosmetics,
href="http://www.macmakeupwholesale.com">wholesale mac makeup
make up, video make

...What a perfect thing, it attracted all the attention, the miraculous birth of

boundless charm. It is worthy of appreciation and ownership.

# Posted By 59.32.56.46 on Monday, August 30 2010 at 9:35 AM

15. Shop popular stores to find juicy couture women's

fashions on sale - all in one place. Find it all here: JC handbags, shoes, tracksuits,

clothing, and more!mac cosmetics
mac makeup
christian louboutin shoes
christian louboutin
links of londonWhat a perfect thing, it attracted

all the attention, the miraculous birth of boundless charm. It is worthy of

appreciation and ownership.

# Posted By 59.32.56.46 on Monday, August 30 2010 at 9:36 AM

16. Find ugg and Australian sheepskin boots, learn the history behind the Ugg boot, and when and what to wear with Cheap ugg boots, as well as cleaning and caring forAuthentic Ugg boots,Cheap ugg cardy boots,20%-40% high discount

# Posted By p on Wednesday, September 1 2010 at 2:08 PM

17. There are many people like to searching the famous brand shoes
online.
Nike Air Max
is always the best choice and you will fall in love when the first sight.As the most sought-after products,
the famous brand shoes
are not only fashionable but also practical.Nike Air Max which is one of the hottest shoes in the summer are available in a variety of styles, colors and materials.
Nike Air Max shoes
are designed for yourself.You can pick up a pair now at www.online268.com.

# Posted By online268 on Wednesday, September 1 2010 at 4:17 PM

18. linda
Gucci Designer handbags are not rightful simple leather lacoste Gucci Outlet men embroidered carrier items imperative for the jurisdiction of girlie items drink in toiletries, make-up and authorize UGG Boots. No girlfriend! An authentic designer MBT Shoes speaks volumes about you and implies that you are a witch of style, seasoning and UGG Boot. However, you power serve as assurance that having an authentic nike dunk is facade your carry through. You Cheap Gucci substitute wonderment if you passion to crack into MBT Discount savvy a blasting move shift you have your pocket dunk shoes and house till you dispatch to that unknown pace when you be credulous saved enough to buy your confess authentic designer bag.

# Posted By nike dunk on Thursday, September 2 2010 at 2:07 AM

19. As we all know, earrings are jewelry attached to the ear through a piercing in the earlobe or some other external part of the ear. Earrings are women's favorite. Proper Tiffany Bangles earrings can not only make a female look more beautiful, but also have the function of accommodating defects. Tiffany Cuff LinksSo it is necessary to know about how to wear earrings properly. Therefore, before you wear , you must take many factors into consideration, such as environment, your temperament, face shape, hairstyle, and your costume to reach the best effect.Wear Tiffany Accessories according to your face shape This will make your face look less plump. If you are long-faced, then you'd better choose Tiffany Sets hoop earrings or big earrings to make your face look more fetching. If you have a square-shape face, then dapper stud earrings, long drop earrings or exaggerated earrings can make you look livelier My discount silver tiffany
necklace
Blog.

# Posted By silver tiffany necklace on Thursday, September 2 2010 at 7:10 AM

20. Louis Vuitton replica
replica louis vuitton
replica handbag
replica bags
replica bag
LV

# Posted By ss on Thursday, September 2 2010 at 7:43 AM

Add a Comment

(If you leave this blank, your IP address will be displayed instead)

(Optional, will not be displayed on the site)