6

Possibly my favourite function is Clojure's "recur", which isn't really a function at all, but a special form that gives you a guaranteed tail-position call to the current function.

Basically what that means is you can write recursive functions (functions that call themselves) and know that you're not creating a potential stack overflow.

Um. Okay, I can feel people looking at me like 🤔 Basically what *that* means is: normally when a function calls another function, a "stack frame" is allocated, holding all the local variables for that call. If a function calls itself 1000 times, 1000 stack frames get allocated. "Tail call optimisation" is a process by which if you call yourself as the very last thing in a function, the language doesn't need to remember the current frame; it just has to pass the return value upwards. The trouble is, it's sometimes hard to notice that you've turned a tail-call optimisable function into a non-optimisable one. Clojure's recur keyword makes it explicit, and therefore safe: if you try to do anything with the return value of recur, it's an error.

PS I'm sure another language did explicit TCR first, but Clojure is where I first saw it.

Comments
  • 0
    @h3ll Yeah, I think it's the same idea.
  • 1
    Oh I really need that in Java. I tend to solve stuff recursivly and some problems are bigger than my stack!
  • 0
    @taumonkeys Both Clojure and Scala run on the JVM. Just throwing that out there ;)
  • 2
    I know. Team of 6. Mixed skills. Company restrictions. Management decisions:
    Plain Java!
  • 1
    Thanks for the interesting lesson! 😀
    If only every programming concept was explained until it was this evident! Like you just did!
  • 1
    @siljamicke I used to be a technical author and it left me with obsessive-compulsive explaining disorder :)
Add Comment