2 ms·
Perhaps I'm missing some larger point here, but if all tail recursive operations can be represented as loops, why not code them that way in the first place? It
by photon_off 16y ago
Perhaps I'm missing some larger point here, but if all tail recursive operations can be represented as loops, why not code them that way in the first place? It's probably better to know that recursive calls take up stack space on each call, than it is to know that tail recursion optimizes to a loop.
If somebody could provide an example of a tail-recursive function that would be much more difficult to code as a loop, I'll eat my words.
- yason 16y agoAs it happens, I've actually grown to like Clojure's recur more than tailcalls. And I much loved tailcalls over imperative loops earlier. recur is still functional, it resembles a loop but isn't one so nothing is mutated, and you can even nest them. And you can recur over a loop or the function itself. Handy.
- _delirium 16y agoThat's fairly common style in Scheme as well, fwiw; a "named let" is very similar to Clojure's recur, and some programmers prefer it over tailcalls, at least for many common recursion/iteration patterns.
- eru 16y agoTake a look at parsers. E.g. Parsec (http://www.haskell.org/haskellwiki/Parsec http://www.haskell.org/haskellwiki/Parsec). They probably have lots of tail-calls, and wouldn't look nice with loops. Some parsers also make use of continuation passing (http://en.wikipedia.org/wiki/Continuation-passing_style http://en.wikipedia.org/wiki/Continuation-passing_style), which only works with tail-call optimizations.