I'm writing this function without using the built in reverse function and therefor having some difficulties
My function must use class constraints to ensure that it will work for lists of integers, floats, and characters. Once I use class constraints my code stops working
Here is my code
reverseList :: [Int] -> [Int]
reverseList [] = []
reverseList (x:xs) = reverseList xs [x]
Here is my code with class constraints
reverseList :: (Eq a) => a -> a
reverseList [] = []
reverseList (x:xs) = reverseList xs [x]
Can anyone help me out? Thanks
CodePudding user response:
The type signature
reverseList :: (Eq a) => a -> a
expresses that this function can accept any input, provided it can be equality-compared (and give a result of that same type). So, you would be able to use this function in ways like
> reverseList 256
> reverseList False
> reverseList pi
> reverseList 'y'
> reverseList (Left "fubar" :: Either String Float)
What could possibly be the result of those?
The signature should instead express that it can accept a list of any type. (BTW, lists are not arrays.)
reverseList :: Eq a => [a] -> [a]
Actually, the Eq
constraint is completely unnecessary, because you never compare the elements in the list, only the list structure. So, the simpler
reverseList :: [a] -> [a]
does the trick as well.
Another remark: your implementation is very inefficient, because
needs to traverse the entire LHS list, but that keeps getting longer and longer as you recurse down – a classic Shlemiel the Painter. Exercise: figure out why the standard implementation does not have this problem.