DEV Community


Discussion on: Tail Recursion

gypsydave5 profile image
David Wickes

Ben, you're a nutter (in the nicest way possible). Tail calls in C++ -- I did not see that coming.

I always think of...

from xkcd

But here you've made the point that tail recursion is not its own reward -- it allows an optimization in C++ and other languages. This is so often missed out when people discuss and teach (and perform) functional programming: we're at the mercy of the compiler as to whether what we're writing is at all performant.

Two examples I always think of:


Although the ES2015 spec requires Tail Call Optimization (TCO), it's supported in barely any of the JS run times! Write some recursive JS and your stack will soon blow!


Arrow, a functional library for Kotlin. Because the Kotlin compiler (should that be 'kompiler'?) is built to optimize for imperative code with a souçon of functional sugar, the 'functional' structures that Arrow supplies are woefully less performant than the equivalent imperative code. I have benchmarks... somewhere...

This makes me think that what makes a 'functional language' functional is very little to do with the actual language, but rather what the compiler / interpreter is optimizing for.

deciduously profile image
Ben Lovy Author

Hah, I've just got C++ on the brain this week! It does optimize for it :) Heaven forbid I stick to a language for two consecutive posts.

I actually didn't know that about JS, way to go Safari. Thanks for pointing that out!

Kotlin has actually been high on my "try-next" list for a while. I had a great time with Clojure, that's one heck of a runtime to be driving, but eventually felt it not practical for what I was working on and Kotlin looks like a great JVM addition a little closer to the mainstream. I'm surprised to hear that there's such a disparity, I thought the langauge was intended to be more functional forward. Do you know if it's a development priority or are most using Kotlin in a more Java-esque style?

gypsydave5 profile image
David Wickes

Do you know if it's a development priority or are most using Kotlin in a more Java-esque style?

From my experience of it Kotlin is trying to be a less awful Java with excellent interop. Some ideas from Groovy, some from Scala. It's got a good (and necessary) story to tell about nulls.

What it isn't is a language like Haskell or Scala, and I don't think it ever will be (or should be).

But it's definitely better than writing Java.