5 ms·
Transforming an accumulating mundane recursive fn into a tail-recursive fn
- eru 16y agoIn Haskell, the decision gets more complicated. It's one of the few functional languages, where you often want to avoid tail-recursion.
- fogus 16y agoCare to elaborate?
- eru 16y agoIn Haskell, foldr can sometimes produce output as soon as it sees the first cons. So you don't have to wait for the whole list, which may be infinite.
- teaspoon 16y agoMaybe you're thinking of `foldl`, which happens to be tail-recursive. The reason it's avoided is because it can unnecessarily eat up O(n) space due to laziness. The issue is avoided by using the strict (and also tail-recursive) `foldl'`.
- eru 16y agoYes. Or depending on what kind of result your fold should produce, you may be better server with foldr, which actually benefits from lazyness.