Haskell reverse function
functional-programming, haskell
Solution
As groovy mentioned, Haskell ranges are mostly incremental - that is, it has no idea how to construct a decreasing list unless you give it some hint. Have a look at a ghci session below:
Prelude> [5..0]
[]
Prelude> [5,4..0]
[5,4,3,2,1,0]
So, you can construct something like this:
foo xs = [(length xs-1), (length xs -2)..0]
rev xs = [xs !! k| k <- foo xs]
which checks out in ghci like this:
Prelude> rev [1..5]
[5,4,3,2,1]
Have a look at Unexpected result while reversing a list and How can I write reverse by foldr efficiently in Haskell? for other ideas on reversing a list.
Problem
Very new to Haskell, and trying to create my own reverse function. Wrote this here, but it always returns an empty list [] : ``` reverse' :: [a] -> [a] reverse' xs = [xs !! k | k <- [((length xs) - 1)..0]] ``` Can anyone explain what I'm doing wrong? Thanks