How can I apply to functions to a list in haskell?

Viewed 106

I'm trying to write a function that checks whether or not a given list is a palindrome. However, I can't figure out how to apply to functions to a given input. My Code looks like this:

isPalindrome :: [a] -> Bool
isPalindrome x
  | head x == last x = True
  | otherwise = isPalindrome tail (init x)

This doesn't work and I cant figure out why.

2 Answers

The main problem with the code is the logic - it is saying "if the head and tails match, it is a palindrome, accept. Otherwise..." The real test is "if the head and tail differ, reject. Otherwise check the center part."

You have to think in the cases, this function does the trick:

isPalindrome []       = True   
isPalindrome [x]      = True   
isPalindrome [x,y]    = x == y 
isPalindrome xs       = (head xs) == (last xs) && isPalindrome ((tail . init) xs)

With an example:

isPalindrome "aabaa"  -->
isPalindrome "aabaa"   = (head "aabaa") == (last "aabaa") && isPalindrome ((tail . init) "aabaa")

next step)

isPalindrome "aabaa"  = ('a') == ('a') && isPalindrome "aba"

next step) isPalindrome "aba"

(head "aba") == (last "aba") && isPalindrome ((tail . init) "aba")

next step ->

('a') == ('a') && isPalindrome "b")

last step ->

isPalindrome "b"
isPalindrome [x]      = True 

so we have the expression:

 ('a') == ('a') && ('a') == ('a') && True --> True
Related