O'Reilly logo

Haskell Cookbook by Yogesh Sajanikar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

There's more...

The interesting thing about this solution is that it uses an internal function that does the recursion. The result of the recursion is stored as an argument. When a special case is hit (such as the list being empty in our example), the result of the recursion is returned. 

The recursion is tail recursion. It means that whenever we recurse, we ensure that the last function that is evaluated is exactly the same function that we are defining. In our example, we always called reverse' function as a top expression. The compiler optimizes the tail recursive functions such that they are executed in constant space and without adding them to stack.

The following diagram shows how a tail recursive function works. The diagram shows how ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required