As far as I know recursion is very elegant but unefficient in OOP and procedural programming (see the wonderful “High Order perl”, Mark Jason Dominus). I had some informations that in functional programming recursion is fast – keeping its elegance and simplicity. Could someone confirm and possibly amplify this? I am thinking in terms of XSLT and Haskell (high on my next-language-to-learn list)
Thanks
Daniel
Tail recursion is iteration in any decent functional language implementation. Here’s an example using GHC Haskell. A simple program to add a sequence of numbers. It begins as the composition of several recursive functions:
Which the compiler optimizes into a single tail recursive function (in a source-to-source transformation):
This recursive function is then compiled into a straight forward loop:
Or with the GHC LLVM backend, additional optimizations are applied to the imperative representation of the program:
Note how the tail recursive label is tagged.
So we had a pipeline of recursive functions, which were compiled to a single tail recursive function, which was compiled to a single imperative loop using no stack. And 8 instructions in the end.
And that is why both function composition, and recursion, are extremely efficient in good, optimizing function languages.