简体   繁体   中英

Verify if a function is a palindrome in haskell

I've tried to use a function that calculate the reverse of a list. So I can use it in other function that will be the palindrome function, but always I get an error. The first one works.

This is the code:

rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]

palindrome :: [a] -> Bool
palindrome [] = True
palindrome (x:xs) = if xs == rev (x:xs) then True else False

I have to mention that I have to do it with that signature: [a] -> Bool

Someday I will muster the energy to put together a megaquestion to address two common beginner list mistakes: thinking that [x] matches a list of any length, and thinking that any function on lists must have [] and x:xs patterns. This question is an example of the latter. When you do the same thing regardless of list length, you don't need multiple patterns! Just palindrome xs = ... is fine. Try writing your palindrome function again with this in mind; your bug will be fixed as a side effect.

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