I'm starting to do my firsts steps in Haskell. I have worked with recursion problems in the past using Python. Just for practice purposes, I'm trying to write a function witch reverse a list:
reverse2 lst = if length lst == 1
then lst !! 0
else (last lst) : (reverse2 (init lst))
I get the error:
SimpleFunctions.hs:9:22: error:
• Occurs check: cannot construct the infinite type: a ~ [a]
• In the expression: (last lst) : (reverse2 (init lst))
In the expression:
if length lst == 1 then
lst !! 0
else
(last lst) : (reverse2 (init lst))
In an equation for ‘reverse2’:
reverse2 lst
= if length lst == 1 then
lst !! 0
else
(last lst) : (reverse2 (init lst))
• Relevant bindings include
lst :: [a] (bound at SimpleFunctions.hs:7:10)
reverse2 :: [a] -> [a] (bound at SimpleFunctions.hs:7:1)
|
9 | else (last lst) : (reverse2 (init lst))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
But if I change by
reverse2 lst = if null lst
then []
else (last lst) : (reverse2 (init lst))
It works!
Why the first option is not correct?