2

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.

Rosarosa
  • 51
  • 6

2 Answers2

3

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."

David Fox
  • 654
  • 4
  • 10
0

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
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • Thank you, however this still doesn't seem to work. When I tried out your code, I got the Compiler Error: ``` 99probs.hs:27:27: error: * No instance for (Eq a) arising from a use of `==' Possible fix: add (Eq a) to the context of the type signature for: isPalindrome :: forall a. [a] -> Bool * In the expression: x == y In an equation for `isPalindrome': isPalindrome [x, y] = x == y 27 | isPalindrome [x,y] = x == y ´´´ Can you explain to me, why that happens? Do I need to add an EQ Typeclass or something? – Rosarosa Aug 04 '21 at 07:48
  • Just don’t add the type to the equation and Haskell will infer it for you – developer_hatch Aug 05 '21 at 04:33
  • What I was saying is don't add this type `isPalindrome :: [a] -> Bool` let haskell infer it for you, try not to adding that line and it will compile – developer_hatch Aug 05 '21 at 16:38