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

How it works...

The reverse function is implemented as follows:

    reverse xs = reverse' xs []

Here, we used an internal reverse' function with an extra argument.

The internal function reverse' is a worker function that actually does the work. Its signature is as follows:

    reverse' :: [a] -> [a] -> [a]

It takes two arguments--the first one is the list that needs to be reversed and the second argument is where we store the result, that is, the reversed list. The recursion is implemented for the worker function reverse'.

There are two base cases for the input list: 

  • Case I--List is empty--Here, we will simply return the second argument, which is where we have stored the result:
        reverse' [] rs = rs
  • Case II--List is not empty--The first element ...

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