Search code examples
haskellfunctional-programming

Reverse a list in haskell


I am trying to reverse a list.

Following is my code:

reverseList :: [Int] -> [Int]
reverseList [] = []
reverseList (x:xs) =  x:reverseList xs

What ends up happening is I end up getting the list back in same order. I even have a solution for how to reverse the list but I am trying to understand what I did wrong here ? I am very new to haskell so think I should focus on understanding more then I can solve more problems with ease. I know there are many solutions out there for this problem but I need more help in the understanding esp what I did wrong here in this code.


Solution

  • You are separating the list into head and tail, but then re-assemble the list in the same order. Take the list [1, 2, 3] for example:

    In the first call, x will be 1, and xs will be [2, 3]. Then you create a new list, consisting of x (so 1) at the front, followed by reverseList [2, 3].