2

I'm working on a palindrome checker in Haskell, but we must use head and last. My error is about the if statement, but I've tried many variations of this and I can't figure out why the if is a problem. Please help! Thank you!

palindrome2::String->Bool
palindrome2 xs = while xs==notEmpty if head xs == last xs then True else False
1
  • 5
    It seems you are trying to imitate an imperative loop from some other language. Don't do that, it will only lead to more confusion. In particular, unless you defined them somewhere else while and notEmpty don't exist at all. Commented Nov 4, 2016 at 1:04

1 Answer 1

2

The easiest way to check if a string is a palindrome would probably be to check if it's equal to the reversed version of itself:

isPalindrome :: String -> Bool
isPalindrome str = str == reverse str

But since you said you have to use head and tail, I'll demonstrate an implementation using these functions:

palindrome2::String -> Bool
palindrome2 [] = True
palindrome2 xs = head xs == last xs && palindrome2 (take (length xs - 2) (tail xs))

I'm not sure what you were trying to do with while. Perhaps some sort of confusion coming from an imperative language? This implementation works recursively, checking if the head of the list is equal to the last term and nesting in to the list if they are equal. Evaluation terminates if the first and last terms are not equal (the string is not a palindrome), or once the base case is reached (the string is a palindrome).

Note that the first implementation is much more efficient.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot! I am just starting to learn so I'm definitely getting used to Haskell after working mostly with object-oriented languages, so my tendency to use while is strong! I knew I needed some kind of loop here, so this helps me understand how I can do it in Haskell with recursion instead. Thanks again!
"Note that the first implementation is much more efficient." -- Indeed. The second implementation is quadratic, as length and last are linear in the length of the list.
@MaryCounts One bonus exercise you might want to try later is implementing isPalindrome without the predefined list manipulation functions (reverse, last, etc.). There is a nice solution for that in the middle of the answer to this Code Review question.
Note that if x then y else False is an antipattern which can be replaced by x && y. The latter reads better: xs is a palindrome iff its tail equals its head and after removing head and tail the result is still palindrome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.