Haskell String Palindrome Check
module PalindromeCheck where -- | Checks if a given string is a palindrome. -- A palindrome is a word, phrase, number, or other sequence of characters -- which reads the same backward as forward. -- This implementation is case-sensitive. isPalindrome :: String -> Bool isPalindrom...
This Haskell function `isPalindrome` determines if a given string reads the same forwards and backward. It employs a recursive approach, comparing the first and last characters of the string. If they match, it recursivel...
The `isPalindrome` function checks for palindromes using recursion. The base cases are an empty string or a single-character string, both of which are considered palindromes and return `True`. For longer strings, it compares the `head` (first character) with the `last` character. If they are equal, it recursively calls `isPalindrome` on the string excluding the first and last characters (`init (tail str)`). If the `head` and `last` characters differ, the string is not a palindrome, and it returns `False`. This recursive structure effectively shrinks the problem space with each call. The time complexity is O(N), where N is the length of the string, because each character is examined at most once. The space complexity is O(N) in the worst case due to the recursion depth, which can be optimized to O(1) with tail-call optimization or an iterative approach if needed, though Haskell's compiler is good at optimizing this. Edge cases like empty strings and single-character strings are handled explicitly.
function isPalindrome(str): if length of str is 0 or 1: return true firstChar = first character of str lastChar = last character of str if firstChar is equal to lastChar: return isPalindrome(substring of str excluding fi...