How to do it...

  1. Change directory to reverse, and open src/Main.hs. This file defines the Main module.
  2. Conditionally import Prelude, hiding the reverse function:
        import Prelude hiding (reverse)
Note that Prelude is imported automatically unless it is explicitly imported. Since we will write our own reverse function, we need to hide the reverse function while importing Prelude
  1. Write the signature of a reverse function:
        reverse :: [a] -> [a]

This function takes a list of any type, a, and returns the reversed list.

  1. Implement the reverse function using recursion:
        reverse :: [a] -> [a]
reverse xs = reverse' xs []
where
reverse' :: [a] -> [a] -> [a]
reverse' [] rs = rs
reverse' (x:xs) rs = reverse' xs (x:rs)

Note that we have a written recursive function. However, this recursive function is an internal function reverse' that takes two arguments.

  1. Use the reverse function in main to test it. Here, we will check whether the function has successfully reversed the list [1..10]:
         main :: IO ()
main = do
let inp = [1..10]
rs = reverse inp
putStrLn $ "Reverse of " ++ (show inp) ++ " is " ++ (show
rs)
  1. If you build the project using stack build and execute it with the command stack exec reverse, you will see the following output:
        Reverse of [1,2,3,4,5,6,7,8,9,10] is [10,9,8,7,6,5,4,3,2,1]