4 ms·
I've been doing some programming with Haskell lately, and what I notice is that almost nothing I write is tail recursive. Why? Because anything that I might wri
by jerf 18y ago
I've been doing some programming with Haskell lately, and what I notice is that almost nothing I write is tail recursive. Why? Because anything that I might write that would be tail recursive uses a combinator (foldX, map, whatever) instead. Only rarely do I write a tail-recursive function, and even for those I'm probably missing some combinator somewhere that could solve my problem.
Python, of course, doesn't use "combinators", but provides loops and iterators and a number of other things that are different, but pretty much just as good. Better some ways, worse others, and that's all you can really ask for from a language since "uniformly better" isn't really on the menu.
The more I learn about functional programming, and modern functional programming in particular, the more this sounds like a gigantic argument over Python not having a compiler optimization that doesn't even make sense for Python anyhow. If you're trying to write a tail recursive function in Python, you've almost certainly passed up a "more Pythonic" solution, which is to say, a solution that is more idiomatic, runs faster, and will make sense to your fellow Python programmers. If you're writing something so painfully functional that you need Python to optimize tail-recursion, it's probably time to get out of Python altogether... it is not a functional language, and while you can dip into old-style functional ("first-order functions", "closures"), it does not and can not do new-style functional ("immutable", "monads", "continuation passing") worth a crap.
Tail recursion is the functional answer to the "private" attribute in OO languages, a language design issue that got falsely enshrined in the paradigm itself as the One True Way to program. It's not. It's a compiler hack, and you don't need it in Python, any more than Python programs come crashing down because they don't have "private" variables. (Yes, I know about double-underscores... all about them. That's why I never use them.) Just as you very nearly don't need tail recursion (directly) in Haskell.
I write fluent Python and Erlang and decent Haskell, and I miss OO in Erlang and Haskell (even a basic purely-functional variant, and yes I know about typeclasses in Haskell and various Erlang hacks, I use some myself; I know how to get it done in the native style) far more often and far more acutely than I miss tail recursion in Python.
- Confusion 18y agoCan I correctly summarize your comment as: "in Python, tail recursion can be considered premature optimization"? In which case I would agree, but wouldn't it be nice if you could 'annotate' specific functions/methods as 'this one is tail recursive, please optimize'?