简体   繁体   中英

I'm writing a Haskell function that tests if an array of elements is a palindrome

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM